I am trying to read a file and then replace all occurrences of "***EndSection***" with "Break" + a number which is incremented for each occurrence of "***EndSection***" . But right now the loop just continues indefinitely.
Here's what I have right now:
int matchCount = 0;
int wordIndex;
DialogResult result;
TextReader tr = new StreamReader(openFileDialog2.FileName);
string text = tr.ReadToEnd();
tr.Close();
string pattern = "***EndSection***";
while (( wordIndex = text.IndexOf(pattern)) != -1)
{
matchCount++;
text.Remove(wordIndex, 16).Insert(wordIndex, "Break"+ matchCount);
}

1 answers
Strings are immutable objects. In other words, once a string object is created, it cannot be modified in place. When you called the Remove() and Insert() methods, you are creating new instances of strings. The text variable (which your loop depends on) is still pointing to the original string that it was assigned so (assuming the pattern is in the string to begin with) the condition will always be true. You need to reassign the "modified" string back into the text variable so the condition will be checked against the new string.
while (( wordIndex = text.IndexOf(pattern)) != -1)
{
matchCount++;
text = text.Remove(wordIndex, 16).Insert(wordIndex, "Break" + matchCount);
}
answered 2 years ago by:
538
Ahh. Thank you.
answered 2 years ago by:
51
This post was imported from csharpfriends, if you have a similiar question please ask it again.
All previous members have been migrated, hope you enjoy the new platform!