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
Release: 2025-01-25 15:47:09
Original
708 people have browsed it

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>
Copy after login

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>
Copy after login

After applying the replacement, the string will become:

<code>1 2 3 4 5</code>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template