基于第一次出现的字符分割字符串

时间:2020-12-15 21:38:00

How can I split a C# string based on the first occurrence of the specified character? Suppose I have a string with value "101,a,b,c,d". I want to split it as 101 & a,b,c,d. That is by the first occurrence of comma character.

如何根据指定字符的第一次出现分割c#字符串?假设我有一个值为“101 a b c d”的字符串。我想把它分成101 & a b c d。这是第一个出现的逗号字符。

4 个解决方案

#1


53  

You can specify how many substrings to return using string.Split:

您可以指定使用字符串返回多少子字符串。

var pieces = myString.Split(new[] { ',' }, 2);

Returns:

返回:

101
a,b,c,d

#2


9  

string s = "101,a,b,c,d";
int index = s.IndexOf(',');
string first =  s.Substring(0, index);
string second = s.Substring(index + 1);

#3


4  

You can use Substring to get both parts separately.

可以使用子字符串分别获取这两个部分。

First, you use IndexOf to get the position of the first comma, then you split it :

首先,使用IndexOf获取第一个逗号的位置,然后将其拆分:

string input = "101,a,b,c,d";
int firstCommaIndex = input.IndexOf(',');

string firstPart = input.Substring(0, firstCommaIndex); //101
string secondPart = input.Substring(firstCommaIndex + 1); //a,b,c,d

On the second part, the +1 is to avoid including the comma.

在第二部分,+1是避免包含逗号。

#4


2  

Use string.Split() function. It takes the max. number of chunks it will create. Say you have a string "abc,def,ghi" and you call Split() on it with count parameter set to 2, it will create two chunks "abc" and "def,ghi".

使用string.Split()函数。马克斯。它将创建的块的数量。假设你有一个字符串“abc,def,ghi”,你在上面调用Split()并将count参数设置为2,它将创建两个块“abc”和“def,ghi”。

#1


53  

You can specify how many substrings to return using string.Split:

您可以指定使用字符串返回多少子字符串。

var pieces = myString.Split(new[] { ',' }, 2);

Returns:

返回:

101
a,b,c,d

#2


9  

string s = "101,a,b,c,d";
int index = s.IndexOf(',');
string first =  s.Substring(0, index);
string second = s.Substring(index + 1);

#3


4  

You can use Substring to get both parts separately.

可以使用子字符串分别获取这两个部分。

First, you use IndexOf to get the position of the first comma, then you split it :

首先,使用IndexOf获取第一个逗号的位置,然后将其拆分:

string input = "101,a,b,c,d";
int firstCommaIndex = input.IndexOf(',');

string firstPart = input.Substring(0, firstCommaIndex); //101
string secondPart = input.Substring(firstCommaIndex + 1); //a,b,c,d

On the second part, the +1 is to avoid including the comma.

在第二部分,+1是避免包含逗号。

#4


2  

Use string.Split() function. It takes the max. number of chunks it will create. Say you have a string "abc,def,ghi" and you call Split() on it with count parameter set to 2, it will create two chunks "abc" and "def,ghi".

使用string.Split()函数。马克斯。它将创建的块的数量。假设你有一个字符串“abc,def,ghi”,你在上面调用Split()并将count参数设置为2,它将创建两个块“abc”和“def,ghi”。