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 ,
Use the String.Substring method
http://msdn.microsoft.com/en-us/library/system.string.substring(v=VS.100).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));
}
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"
.
You could use a string.replace if it is always two commas at the end
http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx
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);