[英]Remove text after a string occurrence
我有一個字符串,具有以下格式:
string sample = "A, ABC, 1, ACS,,"
正如你所看到的,也有5個OCCURENCES ,
字符。 我需要在第4次發生后刪除所有內容 ,以便最終結果為:
string result = fx(sample, 4);
"A, ABC, 1, ACS"
沒有foreach
可能嗎? 提前致謝。
你可以這樣做:
sample.Split(',').Take(4).Aggregate((s1, s2) => s1 + "," + s2).Substring(1);
這將把你的字符串分成逗號,然后只取前四個部分( "A"
, " ABC"
, " 1"
, " ACS"
),將它們連接到一個帶有Aggregate
字符串(結果: ",A, ABC, 1, ACS"
)並返回除第一個字符以外的所有內容。 結果: "A, ABC, 1, ACS"
。
使用String.Substring方法
http://msdn.microsoft.com/en-us/library/system.string.substring(v=VS.100).aspx
你可以使用string.replace,如果它最后總是兩個逗號
如果沒有足夠的逗號來滿足計數,則假設您要返回完整的字符串
String fx(String str, Int32 commaCount)
{
if (String.IsNullOrEmpty(str)) return str;
var i = 0;
var strLength = str.Length;
while ((commaCount-- > 0) && (i != -1) && (i < strLength)) i = str.IndexOf(",", i + 1);
return (i == -1 ? str : str.Substring(i));
}
如果您使用此問題中的GetNthIndex
方法,則可以使用String.Substring
:
public int GetNthIndex(string s, char t, int n)
{
int count = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == t)
{
count++;
if (count == n)
{
return i;
}
}
}
return -1;
}
所以你可以做到以下幾點:
string sample = "A, ABC, 1, ACS,,";
int index = GetNthIndex(sample, ',', 4);
string result = sample.Substring(0, index);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.