换行表示可以依赖于环境的方法:Linux例如使用\n
。
为了方便起见,你可以使用一个StringReader
:
public static IEnumerable<string> Lines (string text) {
string line;
using (StringReader reader = new StringReader(text)) {
while ((line = reader.ReadLine()) != null) {
yield return line;
}
}
}
懒惰评估行:这可能在未来有所帮助,如果你比如有一个巨大的文件,只需要表现出前10行给用户。
然后调用:
return new LinkedList<string>(Lines(text));
编辑:
要获得对,你可以引入一个新的方法:
第二种方法则可以使用拆分项目成对:
public static KeyValuePair<string,string> SplitToKeyValue(string text) {
Regex p = new Regex(@"^(\w+)\s+(.*)$");
Match m = p.Match(text);
return new KeyValuePair<string,string>(m.Groups[1].Value,m.Groups[2].Value);
}
然后cre吃LinkedList
有:使用Mono的csharp
交互shell
return new LinkedList<KeyValuePair<string,string>>(Lines(text).Select(SplitToKeyValue));
DEMO
:
$ csharp
Mono C# Shell, type "help;" for help
Enter statements below.
csharp> using System.IO;
csharp> using System.Text.RegularExpressions;
csharp> public static class Foo {
>
> public static KeyValuePair<string,string> SplitToKeyValue(string text) {
> Regex p = new Regex(@"^(\w+)\s+(.*)$");
> Match m = p.Match(text);
> return new KeyValuePair<string,string>(m.Groups[1].Value,m.Groups[2].Value);
> }
>
> public static IEnumerable<string> Lines (string text) {
> string line;
> using (StringReader reader = new StringReader(text)) {
> while ((line = reader.ReadLine()) != null) {
> yield return line;
> }
> }
> }
>
> }
csharp> string inp = "LOAD =5.01E+10\nMPY $1\nADD $2";
csharp> new LinkedList<KeyValuePair<string,string>>(Foo.Lines(inp).Select(Foo.SplitToKeyValue))
{ [LOAD, =5.01E+10], [MPY, $1], [ADD, $2] }
或fiddle。
在* Windows *环境中,它是'\ r \ n',在* Linux *上,它是'\ n'。 –
你的意思是'var lines = myString.Split(new [] {“\ r \ n”,“\ n”},StringSplitOptions.None).ToList();' – StuartLC
@InfernumDeus:你用什么类型帕尔斯? 'KeyValuePair'? –