How to Trim the String

I have a String like Capture

If i am using Trim Method means, It will trim Left and Right empty Space…
But using Trim Method, the output will comes like this
Capture
But i want to trim the in-between string…like this
Capture
How can i achieve this…???

1 Like

Hey @Poovarasan2

you can use Regex to replace space .

Regex.Replace(“your_str”, “\s+”, “”);

or

you can use string.replace as well to replace space with “”.

Regards…!!
Aksh

4 Likes

Hi,
I hope this will helpful to you…
regex.Replace(str,“\s{2,}”," ")

Regards,

2 Likes

Thank you @aksh1yadav, @Hemanth

string.replace will not work if string contains more than two space as it will loop only once for whole string, say if string is “abc(four space)def” then string.replace will remove only two space, the result will be (“abc(two space)def”).

hello @AkshaySandhu
It is working fine…

On That “\s+” will take only more than one space…

I was talking about string.replace…
regex.replace definitely gonna work but not this Regex.Replace(“your_str”, “\s+”, “”) but this Regex.Replace(“your_str”, “\s+”, “ ”)

Hey @AkshaySandhu

I have mention the alternate option to use it i have not said that string.replace(" ",String.Empty) you are getting right it will replace one space.or if you will pass two space then also it will replace those.

For your information Either you can loop it for example while and check how much space that string contains then remove all with single space then fire your string replacement.

My bad at the time of posting… my level of undersating was different and thought the same understanding for whom i was posting. :slight_smile:

this way as well without loop kind of hard coded :slight_smile:

str.Replace(" "," ").Replace(" "," ").Replace(" "," ").Replace(" "," ")

// replace chaining with 1 space, 2 space, 3 space, 4 space :slight_smile:

Regards…!!
Aksh

2 Likes

I have a Excel header in the Format like " Country Code * ".
But i need the Output as " Country Code ".
without Special Character (*) ? how to Remove Special Character.

1 Like