Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c# find substrings – loop never ends

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Many thanks!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading