Home >Backend Development >C++ >How to Replace Multiple Spaces with a Single Space in C#?

How to Replace Multiple Spaces with a Single Space in C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-25 15:47:09712browse

How to Replace Multiple Spaces with a Single Space in C#?

Replace multiple spaces with a single space in C#

In C# text processing, replacing multiple spaces with a single space is a common task. This operation can be used for formatting, data cleaning, or ensuring the consistency of text strings.

You can use the Regex.Replace method to replace multiple spaces with a single space. This method allows you to perform regular expression-based string replacement. The following line of code demonstrates how to replace multiple spaces with a single space:

<code class="language-csharp">myString = Regex.Replace(myString, @"\s+", " ");</code>

Here, @"s " is a regular expression pattern that matches one or more white space characters (including space, tab, and newline characters). The replacement string is just a space.

Example:

Consider the following input string:

<code>1 2 3  4    5</code>

After applying the replacement, the string will become:

<code>1 2 3 4 5</code>

Bonus Tips:

If you need to handle other character sequences besides spaces, you can modify the regex accordingly. For example, to replace multiple underscores with a single underscore, you can use the following pattern:

<code class="language-csharp">myString = Regex.Replace(myString, @"_+", "_");</code>

The above is the detailed content of How to Replace Multiple Spaces with a Single Space in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn