简体   繁体   中英

Read just a part of a big string

I have a large string to read and it's always different, but one word is always the same. The word is MESSAGE , so if my string reader comes across that word it has to write that whole string to disc. I did some code but it's not working, the if segment never triggers, what is wrong here?

string aLine;
StringReader strRead = new StringReader(str);
aLine = strRead.ReadLine();

if (aLine == "MESSAGE")
{
    //Write the whole file on disc
}

You can use Contains,

if(aLine.Contains("MESSAGE")
{
}

You can use String.Contains

if (aLine.Contains("MESSAGE"))

You can also use String.IndexOf but as index is not relevant here so better to use Contains .

if (aLine.IndexOf("MESSAGE") != -1)

If you need ignore case or Cultrue sensitivity then you IndexOf would provide you overloaded method for it, String.IndexOf(string value, StringComparison comparisonType)

if (aLine.IndexOf("MESSAGE", StringComparison.InvariantCultureIgnoreCase) != -1)

You can change your code to work with Contains .

            string aLine;
            StringReader strRead = new StringReader(str);
            aLine = strRead.ReadLine();

            if (aLine.Contains("MESSAGE"))
            {

              //Write the whole file on disc

            }

I think you might be looking for something like String.IndexOf . In that case you could use the following:

if (aLine.IndexOf("MESSAGE") > -1)
{
    ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM