为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
红颜莎娜 2022-01-15 17:12:35
我需要从第二行string开始,'\r'直到下一个'\r'字符。这是我的字符串中的一个示例string str = "@b\r210.190\r\000.000\r\n";我需要取值210.190,但里面没有 '\r'字符。
查看完整描述

3 回答

?
阿晨1998

TA贡献2037条经验 获得超6个赞

尝试使用Split:


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


  string result = str

    .Split(new char[] { '\r' }, 3)  // split on 3 items at most

    .Skip(1)                        // skip the 1st item 

    .FirstOrDefault();              // take the second item if exists (null if not)

编辑:如果是任意 strings (很可能是null或包含10 亿个字符),我建议IndexOf并且Substring(因为Split创建了一个可能不需要的数组):


  int from = str == null ? -1 : str.IndexOf('\r');

  int length = from < 0 ? -1 : str.IndexOf('\r', from + 1) - from;


  string result = length >= 0 ? str.Substring(from + 1, length) : null;


查看完整回答
反对 回复 2022-01-15
?
qq_笑_17

TA贡献1818条经验 获得超7个赞

建议使用Split method,但我认为 Dmitry Bychenko 的回答可以更简单地说:

string result = str.Split('\r')[1];

这是一个在线演示:https ://ideone.com/6Kedjj

正如 Dmitry Bychenko解释的那样,即使您只对第二项感兴趣,这也可能会导致创建一个长数组。这可以通过将输出限制为三个匹配来防止:

string result = str.Split(new char[] {'\r'}, 3)[1];

第一个参数看起来很复杂,但在同一个字符数组中,只有一个元素实际上在第一个版本中使用。(为了完整性,更新的演示:https ://ideone.com/TimaHP )


查看完整回答
反对 回复 2022-01-15
?
BIG阳

TA贡献1859条经验 获得超6个赞

您也可以为此使用正则表达式模式匹配。方法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


查看完整回答
反对 回复 2022-01-15
  • 3 回答
  • 0 关注
  • 209 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号