Trying to replace all white space with a single sp

2019-04-19 16:07发布

问题:

Any ideas?

My program is a file validation utility and I have to read in a format file then parse out each line by a single space. But obviously, the person who wrote the format file may use tabs, or 2 spaces, or any form of whitespace, and I'm looking for some code to do that. I've tried this:

        public static string RemoveWhitespace(this string line) 
        {
            try 
            { 
                return new Regex(@"\s*").Replace(line, " "); 
            } 
            catch (Exception) 
            { 
                return line; 
            }
        }

I'm assuming this is wrong.
Help!

回答1:

You can do this -

System.Text.RegularExpressions.Regex.Replace(str,@"\s+"," ");

where str is your string.



回答2:

input = input.Replace("\t", " ");

List<string> empties = new List<string>();
for (int i=input.Length - 1; i>1; i--)
{
    string spcs = "";
    for (int j=0; j<=i; j++)
        spcs += " ";
    if (input.Contains(spcs))
        empties.Add(spcs);
}

foreach (string s in empties)
    input = input.Replace(s, " ");


回答3:

This is a duplicate of this question

however the answer is this (credit to Daok)

Regex regex = new Regex(@"[ ]{2,}");     
tempo = regex.Replace(tempo, @" ");