为每个冒号“:”分割长字符串,并按位置获取行的索引

时间:2018-09-23 23:34:17

标签: c#

我正在努力理解使用Split方法接收我想要的文本 我收到了来自用户的长注册字符串,并试图按冒号:进行拆分,对于找到的每个冒号,我想获取所有文本,直到行

中的/n为止

我从用户收到的字符串的格式如下所示:

"Username: Jony \n
 Fname: Dep\n
 Address: Los Angeles\n
 Age: 28\n
 Date: 11/01:2001\n"

那是我的做法,直到现在为止还没有弄清楚它是如何工作的,也没有找到像我的问题一样的模拟问题

str = the long string

List<string> names = str.ToString().Split(':').ToList<string>();
names.Reverse();

var result = names[0].ToString();
var result1 = names[1].ToString();

Console.WriteLine(result.Remove('\n').Replace(" ",string.Empty));
Console.WriteLine(result1.Remove('\n').Replace(" ",string.Empty));

2 个答案:

答案 0 :(得分:5)

基准

----------------------------------------------------------------------------
Mode             : Release (64Bit)
Test Framework   : .NET Framework 4.7.1 (CLR 4.0.30319.42000)
----------------------------------------------------------------------------
Operating System : Microsoft Windows 10 Pro
Version          : 10.0.17134
----------------------------------------------------------------------------
CPU Name         : Intel(R) Core(TM) i7-3770K CPU @ 3.50GHz
Description      : Intel64 Family 6 Model 58 Stepping 9
Cores (Threads)  : 4 (8)      : Architecture  : x64
Clock Speed      : 3901 MHz   : Bus Speed     : 100 MHz
L2Cache          : 1 MB       : L3Cache       : 8 MB
----------------------------------------------------------------------------

结果

--- Random characters -------------------------------------------------
| Value |   Average |   Fastest |   Cycles | Garbage | Test |    Gain |
--- Scale 1 -------------------------------------------- Time 1.152 ---
| split |  4.975 µs |  4.091 µs | 20.486 K | 0.000 B | N/A  | 71.62 % |
| regex | 17.530 µs | 14.029 µs | 65.707 K | 0.000 B | N/A  |  0.00 % |
-----------------------------------------------------------------------

原始答案

您可以使用regex,也可以仅使用Split

var input = "Username: Jony\n Fname: Dep\nAddress: Los Angeles\nAge: 28\nDate: 11/01:2001\n";

var results = input.Split(new []{'\n'}, StringSplitOptions.RemoveEmptyEntries)
                .Select(x => x.Split(':')[1].Trim());

foreach (var result in results)
   Console.WriteLine(result);

Full Demo Here

输出

Jony
Dep
Los Angeles
28
11/01

注意:此操作不会进行错误检查,因此,如果您的字符串中不包含冒号,则它会中断


其他资源

String.Split Method

  

返回一个字符串数组,该数组包含此实例中的子字符串   由指定的字符串或Unicode元素分隔的   字符arr

StringSplitOptions Enum

  

指定适用的Split方法重载是包含还是省略   返回值中的空子字符串

String.Trim Method

  

返回一个新字符串,其中所有前导和尾随出现   当前String对象中的一组指定字符是   删除。

Enumerable.Select Method

  

将序列的每个元素投影为新形式。

答案 1 :(得分:2)

您可以使用正则表达式在冒号后直到换行符前找到匹配项:

(?<=:)\s*[^\n]*

regex使用回头法,确保字符串前面有一个冒号,然后它匹配所有不是Newline =其余部分的内容。

像这样使用它:

string searchText = "Username: Jony\n
 Fname: Dep\n
 Address: Los Angeles\n
 Age: 28\n
 Date: 11/01:2001\n";

Regex myRegex = new Regex("(?<=:)\s*[^\n]*");
foreach (Match match in myRegex.Matches(searchText))
{
    DoSomething(match.Value);
}