简体   繁体   中英

Detecting where a newline is located in a string:

I see using the Visual Studio object viewer that my string is:

"_profileIconId = 5\n            elo"

What I need to get the text from beginning to where the newline is.

Here's what I've tried, but the IndexOf() method returns -1, meaning a newline isn't found.

var stringEx = "_profileIconId = 5\n            elo";
var x = stringEx.IndexOf(Environment.NewLine);
stat.Name = tempName.Substring(0,x);

Any ideas on how to accomplish this?

That's because Environment.NewLine represents \\r\\n (a carriage return + line feed) whereas you only have a line feed in your source string. Change the second line to this:

var x = stringEx.IndexOf("\n");

If you just want the first line of the string, you could do this:

static string GetFirstLine(string text)
{
    using (var reader = new StringReader(text))
    {
        return reader.ReadLine();
    }
}

The StringReader class deals with various line-break scenarios for you. From the MSDN documentation :

A line is defined as a sequence of characters followed by a line feed ("\\n"), a carriage return ("\\r"), or a carriage return immediately followed by a line feed ("\\r\\n").

Of course, if you don't want the overhead of constructing a new StringReader object (though I doubt it's that big), you could implement something similar yourself:

static string GetFirstLine(string text)
{
    int? newlinePos = GetIndex(text, "\r") ?? GetIndex(text, "\n");

    if (newlinePos.HasValue)
    {
        return text.Substring(0, newlinePos.Value);
    }

    return text;
}

// Not really necessary -- just a convenience method.
static int? GetIndex(string text, string substr)
{
    int index = text.IndexOf(substr);
    return index >= 0 ? (int?)index : null;
}

If you're running on a Windows platform, Environment.NewLine will look for "\\r\\n".

Try looking for \\n instead:

var x = stringEx.IndexOf("\n");

Here's a general way to do this that will remove a new line and everything after it from the string, but only when a new line exists in the string:

int x = stringEx.IndexOf("\n");

if (x > 0) {
  stringEx= stringEx.Remove(x);
}

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