-1

Is there a method that will remove a set amount of characters from a string, placing the removed characters into a separate string and leaving the original x amount of characters shorter?

I need to parse a string into 10 individual strings, each 10 characters long. I would like to be able to do sommething simple like this, but I do not know if there is a method that works like this in C#

string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
    errorCodes[i] = retrievedMessage.removeFromSubstring(0, 10);
}
4

4 回答 4

1

编辑

现在经过测试,对我来说似乎工作正常

        var errorCodes = "longstringgggggggggggggggggggggggggg";
        var count = 10;
        List<string> s = new List<string>();
        for (int i = 0; i < errorCodes.Length; i += count)
        {
            if (i + count > errorCodes.Length)
                count = errorCodes.Length - i;
            s.Add(errorCodes.Substring(i, count));
        }

        foreach (var str in s)
            Console.WriteLine(str);

        Console.ReadLine();
于 2013-06-05T19:41:10.133 回答
1

你可以试试这个:

string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
    errorCodes[i] = retrievedMessage.Substring(0, 10);
    retrievedMessage = retrievedMessage.Substring(10);
}

该行将retrievedMessage = retrievedMessage.Substring(10);有效地从原始字符串中删除前 10 个字符。这样,在每次迭代中,您将能够使用前 10 个字符并将它们分配给errorCodes[i]

您也可以尝试避免使用子字符串:

string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
    errorCodes[i] = retrievedMessage.Substring(i*10, 10);
}
于 2013-06-05T19:41:45.073 回答
1

这应该适合你

string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
    errorCodes[i] = retrievedMessage.Substring(10*i, 10);
}

这是一个将从string retrievedMessage

string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
    //option to remove from string
    errorCodes[i] = retrievedMessage.Substring(0, 10);
    retrievedMessage = retrievedMessage.Remove(0,10);  //will remove from string
}
于 2013-06-05T19:42:28.043 回答
0

与其他答案相同的基本概念,但对可变字符串长度进行了一些检查。如果您知道您的字符串长度始终为 100 个字符,请使用更简单的答案之一。

string[] errorCodes = new string[10];
for (int i = 0; i < errorCodes.Length; i++)
{
    int startIndex = i * 10;
    if (retrievedMessage.Length > startIndex)
    {
        int length = 10;
        if (retrievedMessage.Length < (startIndex + length))
        {
            length = retrievedMessage.Length - startIndex;
        }
        errorCodes[i] = retrievedMessage.Substring(startIndex, length);
    }
}

注意:由于errorCodes总是以 10 的长度实例化,因此如果 retrievedMessage 的长度 <= 90,这将有空字符串。如果您期望可变长度,最好使用 aList<string>而不是 a string[]

于 2013-06-05T19:45:17.463 回答