Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

like image 292
Raffaeu Avatar asked Feb 23 '11 14:02

Raffaeu


People also ask

How do you delete everything after a certain character in a string?

To remove everything after a specific character in a string:Use the String. split() method to split the string on the character. Access the array at index 0 . The first element in the array will be the part of the string before the specified character.

How do I extract text before and after a specific character in Excel?

To get text following a specific character, you use a slightly different approach: get the position of the character with either SEARCH or FIND, subtract that number from the total string length returned by the LEN function, and extract that many characters from the end of the string.


1 Answers

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".

like image 155
Daniel Hilgarth Avatar answered Oct 15 '22 03:10

Daniel Hilgarth