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.
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.
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.
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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With