[英]Split string based on the first occurrence of the character
如何根據指定字符的第一次出現拆分 C# 字符串? 假設我有一個帶值的字符串:
101,a,b,c,d
我想將其拆分為
101
a,b,c,d
即第一次出現逗號字符。
您可以使用string.Split
指定要返回的子字符串string.Split
:
var pieces = myString.Split(new[] { ',' }, 2);
返回:
101
a,b,c,d
string s = "101,a,b,c,d";
int index = s.IndexOf(',');
string first = s.Substring(0, index);
string second = s.Substring(index + 1);
您可以使用Substring
分別獲取兩個部分。
首先,您使用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
在第二部分, +1
是為了避免包含逗號。
使用string.Split()
函數。 它需要最大值。 它將創建的塊數。 假設您有一個字符串“abc,def,ghi”,並且您在其上調用 Split() 並將count
參數設置為 2,它將創建兩個塊“abc”和“def,ghi”。 確保將其string.Split(new[] {','}, 2)
,這樣 C# 就不會將它與其他重載混淆。
在 .net Core 中,您可以使用以下內容;
var pieces = myString.Split(',', 2);
返回:
101
a,b,c,d
var pieces = myString.Split(',', 2);
這行不通。 重載將不匹配,編譯器將拒絕它。
所以它必須是:
char[] chDelimiter = {','};
var pieces = myString.Split(chDelimiter, 2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.