YosiFZ
YosiFZ

Reputation: 7900

Remove space from String

I have a lot of strings that look like this:

current            affairs

and i want to make the string be :

current affairs

i try to use Trim() but it won't do the job

Upvotes: 4

Views: 335

Answers (6)

Jainendra
Jainendra

Reputation: 25143

Using Regex here is the way,

System.Text.RegularExpressions.Regex.Replace(input, @”\s+”, ” “);

This will removes all whitespace characters including tabs, newlines etc.

Upvotes: 0

evanxg852000
evanxg852000

Reputation: 289

First you need to split the whole string and then apply trim to each item.

  string [] words = text.Split(' ');
  text="";
  forearch(string s in words){
    text+=s.Trim();
  }
  //text should be ok at this time

Upvotes: -1

Roberto Conte Rosito
Roberto Conte Rosito

Reputation: 2098

You can use a regex:

public string RemoveMultipleSpaces(string s) 
{
    return Regex.Replace(value, @"\s+", " ");
}

After:

string s = "current            affairs  ";
s = RemoveMultipleSpaces(s);

Upvotes: 0

Ste
Ste

Reputation: 1136

Use a regular expression.

yourString= Regex.Replace(yourString, @"\s+", " ");

Upvotes: 0

Shakti Singh
Shakti Singh

Reputation: 86346

Regex can do the job

string_text = Regex.Replace(string_text, @"\s+", " ");

Upvotes: 11

Oded
Oded

Reputation: 498934

You can use regular expressions for this, see Regex.Replace:

var normalizedString = Regex.Replace(myString, " +", " ");

If you want all types of whitespace, use @"\s+" instead of " +" which just deals with spaces.

var normalizedString = Regex.Replace(myString, @"\s+", " ");

Upvotes: 6

Related Questions