Asked  7 Months ago    Answers:  2   Viewed   35 times

How can I replace multiple spaces in a string with only one space in C#?

Example:

1 2 3  4    5

would be:

1 2 3 4 5

 Answers

41
string sentence = "This is a sentence with multiple    spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);     
sentence = regex.Replace(sentence, " ");
Tuesday, June 1, 2021
 
Zach
answered 7 Months ago
75

A version that modifies the string in place, run it on a copy if the original must be preserved:

void compress_spaces(char *str)
{
    char *dst = str;

    for (; *str; ++str) {
        *dst++ = *str;

        if (isspace(*str)) {
            do ++str; 

            while (isspace(*str));

            --str;
        }
    }

    *dst = 0;
}
Friday, July 30, 2021
 
Crashthatch
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share