Home > Mobile >  c# find substrings - loop never ends
c# find substrings - loop never ends

Time:10-18

yet another string/substring topic:

I'm trying to write a function that looks for the substrings "id" and "imagePath" in a string that's generated from a very long text file. The characters between the 2 substrings should be written in a rich text box. I cannot see what I'm doing wrong, but the loop never ends and always prints only the first occurrence of said characters, resulting in a million lines that are identical being shown in the text box. There are at least 10 occurrences of both substrings in my file, and my code is below:

private void textToFind ( string file, string catalogType)
        {
            richTextBox1.Clear();
            catalogType.ToUpper();
            string contentOfFile = File.ReadAllText(file);
            contentOfFile.TrimEnd();
            int startPosition, endPosition;
            while (contentOfFile.Length > 20)
            {
                startPosition = contentOfFile.IndexOf("id");
                endPosition = contentOfFile.IndexOf("imagePath");
                if (startPosition >= 0 && endPosition > startPosition)
                {
                    startPosition = startPosition   4;
                    endPosition = endPosition -3;
                    string dataToExtract = contentOfFile.Substring(startPosition, endPosition);
                    richTextBox1.AppendText(dataToExtract   "\r\n");
                    contentOfFile.Remove(startPosition-4, endPosition 12);
                }
                else
                { 
                    richTextBox1.AppendText("fail "   catalogType   "\r\n");
                    contentOfFile.Remove(contentOfFile.Length/2);
                }
            }
            return;
        }

Can anyone please share why this is not working as intended?? I think contentOfFile.Remove is not working and the main string doesn't get trimmed, but I don't understand why.

Many thanks!

CodePudding user response:

contentOfFile.Remove doesn't actually modify the value of contentOfFile it just returns a string that has the specified portion removed.

So you need to do contentOfFile = contentOfFile.Remove(startPosition - 4, endPostion 12);

and same thing with the TrimEnd call before the while loop.

  • Related