c# - 从字符串开始的第二行开始 - 直到

标签 c# string

我需要从 string 中提取 second line,它从 '\r' 开始直到下一个 '\r' 字符。

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

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

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

最佳答案

尝试使用拆分:

  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)

编辑:如果是任意 string(可以是null 或包含 10 亿 个字符)我建议使用IndexOfSubstring(因为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;

关于c# - 从字符串开始的第二行开始 - 直到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52307484/

相关文章:

javascript - 检测 HTML 元素是否分配了 javascript 函数

C# String.Format() 在 PHP 中等效?

java - 如何将字符串转换为数组?

c++ - 分配字符串 uint8_t

java - String hashCode() 文档与实现

c# - 如何在高度可靠的批量传输期间减少 TCP ACK 的数量

c# - Unity2D 拍摄对象随角色转动但不应该转动

c# - 如何在Caliburn.Micro ViewModel中处理WPF MenuItem命令?

python - 将包含\x01 字符的字符串保存到磁盘

c++ - 在运行时将 char 数组转换为 String?