string.remove的问题(signtint,neimint)

克里斯托弗

新成员
加入
2011年8月5日
消息
2
编程经验
5-10
  while (blockfound == true)                {
                    if (plaintext.Length > 32)
                    {
                        plaintextblocks[x] = plaintext.Substring(0,31);
                        blockfound = true;
                        plaintext.Remove(0,31);
                        x = x + 1;
                    }
                    else
                    {
                        plaintextblocks[x] = plaintext;
                        blockfound = false;
                    }
                }


这里的目标是将明文分成32个字符的长块。但是,它也不会删除块,因为它也意味着它只是不断循环。任何人都有任何想法为什么?
 

jmplhinney.

C#论坛主持人
工作人员
加入
2011年4月23日
消息
3,732
地点
悉尼,澳大利亚
编程经验
10+
对于未来的参考,您需要为Xcode标记指定一个选项,以便它知道要使用的语法。如果您是编辑器工具栏按钮,则指定"c#"(没有引号)作为选项,或者如果手动键入标签,则必须打开
.

As for the issue, the answer is in the documentation, which should be the first thing you read when you had a problem.[QUOTE=MSDN]This method does not modify the value of the current instance. Instead, it returns a new string in which the number of characters specified by the count parameter have been removed. The characters are removed at the position specified by startIndex.[/QUOTE]That is the same for all string methods because String objects are immutable, i.e. they cannot be changed once created.

That said, you really shouldn't use Remove at all in this case.  You should just be calling Substring with a different index each time, e.g.[xcode=c#]var text = "12345678901234567890";
var startIndex = 0;
var blockSize = 6;
var blocks = new List<string>();

do
{
    blocks.Add(text.Substring(startIndex, Math.Min(blockSize, text.Length - startIndex)));
    startIndex += blockSize;
} while (startIndex < text.Length - 1);

foreach (var block in blocks)
{
    MessageBox.Show(block);
}
您也可以替换这一点:
blocks.Add(text.Substring(startIndex, Math.Min(blockSize, text.Length - startIndex)));
有了这个:
blocks.Add(new string(text.Skip(startIndex).Take(blockSize).ToArray()));
 
最佳 底部