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. I need to remove everything after the 4th occurrence so that the final result will be:
string result = fx(sample, 4);
"A, ABC, 1, ACS"
Is it possible without a 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. Result: "A, ABC, 1, ACS"
.
Use the String.Substring method
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
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
:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.