String.Split仅在C#中第一个分离器?

编程入门 行业动态 更新时间:2024-10-19 17:37:05
本文介绍了String.Split仅在C#中第一个分离器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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#中第一个分离器?

本文发布于:2023-11-13 00:39:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582930.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:第一个   分离器   String   Split

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!