Delete text after line appears

I have a line that has the following format:

string sample = "A, ABC, 1, ACS,," 

As you can see, there are 5 occurrences of the character,. I need to delete everything after the 4th appearance so that the final result is:

 string result = fx(sample, 4); "A, ABC, 1, ACS" 

Is this possible without foreach ? Thanks in advance.

+4
source share
5 answers

You can do something like this:

 sample.Split(',').Take(4).Aggregate((s1, s2) => s1 + "," + s2).Substring(1); 

This will split your line into a comma and then take only the first four parts ( "A" , " ABC" , " 1" , " ACS" ), split them into one line using Aggregate (result: ",A, ABC, 1, ACS" ) and return everything except the first character. Result: "A, ABC, 1, ACS" .

+12
source

You can use string.replace if there are two commas at the end

http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx

0
source

Assuming you want to return a full line if there are not enough commas to satisfy the score

 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)); } 
0
source

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 can do the following:

 string sample = "A, ABC, 1, ACS,,"; int index = GetNthIndex(sample, ',', 4); string result = sample.Substring(0, index); 
0
source

Source: https://habr.com/ru/post/1340972/


All Articles