猿问

从开始的字符串中取第二行 - 直到

我需要从第二string开始,'\r'直到下一个'\r'字符。

这是我的字符串中的一个示例

string str = "@b\r210.190\r\000.000\r\n";

我需要取值210.190,但里面没有 '\r'字符。


红颜莎娜
浏览 247回答 3
3回答

阿晨1998

尝试使用Split:&nbsp; string str = "@b\r210.190\r\000.000\r\n";&nbsp; string result = str&nbsp; &nbsp; .Split(new char[] { '\r' }, 3)&nbsp; // split on 3 items at most&nbsp; &nbsp; .Skip(1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // skip the 1st item&nbsp;&nbsp; &nbsp; .FirstOrDefault();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // take the second item if exists (null if not)编辑:如果是任意 strings (很可能是null或包含10 亿个字符),我建议IndexOf并且Substring(因为Split创建了一个可能不需要的数组):&nbsp; int from = str == null ? -1 : str.IndexOf('\r');&nbsp; int length = from < 0 ? -1 : str.IndexOf('\r', from + 1) - from;&nbsp; string result = length >= 0 ? str.Substring(from + 1, length) : null;

qq_笑_17

我还建议使用Split&nbsp;method,但我认为 Dmitry Bychenko 的回答可以更简单地说:string&nbsp;result&nbsp;=&nbsp;str.Split('\r')[1];这是一个在线演示:https ://ideone.com/6Kedjj正如 Dmitry Bychenko解释的那样,即使您只对第二项感兴趣,这也可能会导致创建一个长数组。这可以通过将输出限制为三个匹配来防止:string&nbsp;result&nbsp;=&nbsp;str.Split(new&nbsp;char[]&nbsp;{'\r'},&nbsp;3)[1];第一个参数看起来很复杂,但在同一个字符数组中,只有一个元素实际上在第一个版本中使用。(为了完整性,更新的演示:https&nbsp;://ideone.com/TimaHP )

BIG阳

您也可以为此使用正则表达式模式匹配。方法Regex.Match搜索指定正则表达式的第一次出现:string str = "@b\r210.190\r\000.000\r\n";var resultString = Regex.Match(str, @"(?<=\r).+?(?=\r)").Value;Console.WriteLine(resultString + " " + resultString.Contains("\r"));输出: 210.190 False
随时随地看视频慕课网APP
我要回答