C#检查字符串长度是否为188

时间:2019-03-07 09:38:32

标签: c#

在查看@DanielBrughera代码后,他需要使用他的方法,谢谢Daniel Brughera。

string inputtemplate = "00000000000000000000input0000000061306465643436000100000000000000input0000000000613064656434360001000000000000005bd0a47500000000000000000000000000000000";
string wordtoreplace = "input";
List<string> inputs = new List<string>() { "11antigeek11", "1antigeek11" };
foreach(string s in inputs)
{
int inputindex = inputtemplate.IndexOf(wordtoreplace);
if(inputindex < 0)
    Throw new Exception("Input not found");

string tmp;

if(s.Length < wordtoreplace.Length)
{
    tmp = String.Concat(s, new String('0', wordtoreplace.Length - s.Length));
}
else if(s.Length > wordtoreplace.Length)
{
    tmp = inputtemplate.Substring(inputindex, s.Length);
    if(tmp != String.Concat(wordtoreplace, new String('0', s.Length - wordtoreplace.Length)
        Throw new Exception("Input value is too long");
    else
        tmp = s;
}

inputtemplate = inputtemplate.Remove(inputindex, tmp.Length);
inputtemplate = inputtemplate.Insert(inputindex, tmp);
}

我想再次感谢您,丹尼尔·布鲁盖拉。

1 个答案:

答案 0 :(得分:0)

那样,您将始终获得与inputtemplate相同的长度,以防万一您需要使用可编辑的空格(0),我提供了一个验证以防止覆盖其他值...

string inputtemplate = "00000000000000000000input0000000061306465643436000100000000000000input0000000000613064656434360001000000000000005bd0a47500000000000000000000000000000000";
string wordtoreplace = "input";
List<string> inputs = new List<string>() { "11antigeek11", "1antigeek11" };
foreach(string s in inputs)
{
    int inputindex = inputtemplate.IndexOf(wordtoreplace);
    if(inputindex < 0)
        Throw new Exception("Input not found");

    string tmp;

    if(s.Length < wordtoreplace.Length)
    {
        tmp = String.Concat(s, new String('0', wordtoreplace.Length - s.Length));
    }
    else if(s.Length > wordtoreplace.Length)
    {
        tmp = inputtemplate.Substring(inputindex, s.Length);
        if(tmp != String.Concat(wordtoreplace, new String('0', s.Length - wordtoreplace.Length)
            Throw new Exception("Input value is too long");
        else
            tmp = s;
    }

    inputtemplate = inputtemplate.Remove(inputindex, tmp.Length);
    inputtemplate = inputtemplate.Insert(inputindex, tmp);
}