String.Split方便的分隔符分割字符串在多个部分。
我应该如何去只在第一个分隔符分割字符串。例如。我有一个字符串
时间:10:12:12 \ r \ N和我想要一个数组看起来像
{时间,10:12:12 \ r \ N}解决方案
最好的方法取决于一点你要如何灵活的解析是,关于可能的额外空间和这样的。检查的具体格式规范,看看你需要什么。
yourString.Split(新的char [] {':'},2)
会限制你们两个2子。然而,这并不在第二字符串的开头修剪的空间。你可以这样做,在第二次手术但拆分后。
yourString.Split(新的char [] {':',''},2, StringSplitOptions.RemoveEmptyEntries)
应该工作,但将打破,如果你试图分裂包含空格的头名。
yourString.Split(新的String [] {:},2, StringSplitOptions.None);
将不正是你的描述,但实际上需要的空间是present。
yourString.Split(新的String [] {:,:},2, StringSplitOptions.None);
使得空间可选的,但你还是要 TrimStart()的情况下,一个以上的空间。
要保持格式有所灵活,和你的code可读,我建议使用第一个选项:
的String []分割= yourString.Split(新的char [] {':'},2); //可选检查split.Length这里 拆分[1] =分裂[1] .TrimStart();String.Split is convenient for splitting a string with in multiple part on a delimiter.
How should I go on splitting a string only on the first delimiter. E.g. I've a String
"Time: 10:12:12\r\n"And I'd want an array looking like
{"Time","10:12:12\r\n"}解决方案
The best approach depends a little on how flexible you want the parsing to be, with regard to possible extra spaces and such. Check the exact format specifications to see what you need.
yourString.Split(new char[] { ':' }, 2)Will limit you two 2 substrings. However, this does not trim the space at the beginning of the second string. You could do that in a second operation after the split however.
yourString.Split(new char[] { ':', ' ' }, 2, StringSplitOptions.RemoveEmptyEntries)Should work, but will break if you're trying to split a header name that contains a space.
yourString.Split(new string[] { ": " }, 2, StringSplitOptions.None);Will do exactly what you describe, but actually requires the space to be present.
yourString.Split(new string[] { ": ", ":" }, 2, StringSplitOptions.None);Makes the space optional, but you'd still have to TrimStart() in case of more than one space.
To keep the format somewhat flexible, and your code readable, I suggest using the first option:
string[] split = yourString.Split(new char[] { ':' }, 2); // Optionally check split.Length here split[1] = split[1].TrimStart();
更多推荐
String.Split仅在C#中第一个分离器?
发布评论