Issues with String.Remove(startint,endint)

Christopherx

New member
Joined
Aug 5, 2011
Messages
2
Programming Experience
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;
                    }
                }


The aim here is to split up the plaintext into 32 character long chunks. However, it doesn't remove the chunk when I want it too, meaning it just constantly loops. Anyone got any ideas why?
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,272
Location
Sydney, Australia
Programming Experience
10+
For future reference, you need to specify an option for the xcode tags so that it knows what syntax to use. If you the editor toolbar button then specify "c#" (without quotes) as the option or, if you type the tags manually then you must open with
.

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);
}
You could also replace this:
blocks.Add(text.Substring(startIndex, Math.Min(blockSize, text.Length - startIndex)));
with this:
blocks.Add(new string(text.Skip(startIndex).Take(blockSize).ToArray()));
 

Christopherx

New member
Joined
Aug 5, 2011
Messages
2
Programming Experience
5-10
Thanks for the code. Works like a charm. I apologise for the messy post and not reading the documentation. I got quite frustrated so I just posted and asked for help. Thankyou :)
 
Top Bottom