[英]Remove text after a string occurrence
I have a string that has the following format: 我有一个字符串,具有以下格式:
string sample = "A, ABC, 1, ACS,,"
As you can see, there are 5 occurences of the ,
character. 正如你所看到的,也有5个OCCURENCES
,
字符。 I need to remove everything after the 4th occurrence so that the final result will be: 我需要在第4次发生后删除所有内容 ,以便最终结果为:
string result = fx(sample, 4);
"A, ABC, 1, ACS"
Is it possible without a foreach
? 没有
foreach
可能吗? Thanks in advance. 提前致谢。
You could do something like this: 你可以这样做:
sample.Split(',').Take(4).Aggregate((s1, s2) => s1 + "," + s2).Substring(1);
This will split your string at the comma and then take only the first four parts ( "A"
, " ABC"
, " 1"
, " ACS"
), concat them to one string with Aggregate
(result: ",A, ABC, 1, ACS"
) and return everything except the first character. 这将把你的字符串分成逗号,然后只取前四个部分(
"A"
, " ABC"
, " 1"
, " ACS"
),将它们连接到一个带有Aggregate
字符串(结果: ",A, ABC, 1, ACS"
)并返回除第一个字符以外的所有内容。 Result: "A, ABC, 1, ACS"
. 结果:
"A, ABC, 1, ACS"
。
Use the String.Substring method 使用String.Substring方法
http://msdn.microsoft.com/en-us/library/system.string.substring(v=VS.100).aspx http://msdn.microsoft.com/en-us/library/system.string.substring(v=VS.100).aspx
You could use a string.replace if it is always two commas at the end 你可以使用string.replace,如果它最后总是两个逗号
http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx
Assuming that you want to return the full string if there aren't enough commas to satisfy the count 如果没有足够的逗号来满足计数,则假设您要返回完整的字符串
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));
}
If you use the GetNthIndex
method from this question , you can use String.Substring
: 如果您使用此问题中的
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;
}
So you could do the following: 所以你可以做到以下几点:
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.