How to replace consecutive whitespace characters with a single space in C#

2 Answers

0 votes
using System;
using System.Linq;
 
public class Program
{
    public static string ReplaceWhiteSpaces(string str) {
        char[] delimiters = new char[] { ' ', '\t', '\r', '\n'};
        
        return String.Join(" ", str.Split(delimiters).Where(s => !String.IsNullOrWhiteSpace(s)));
    }
    
    public static void Main()
    {
        string str = @"c#   c       python  
                    java";
 
        str = ReplaceWhiteSpaces(str);
        
        Console.WriteLine(str);
    }
}
 

 
 
  
/*
run:
 
c# c python java
 
*/

 



answered Mar 28, 2023 by avibootz
0 votes
using System;

public static class StringTools
{
    public static string ReplaceWhiteSpaces(this string str) {
        char[] whitespace = new char[] { ' ', '\t', '\r', '\n'};
        
        return String.Join(" ", str.Split(whitespace, StringSplitOptions.RemoveEmptyEntries));
    }
}
 
public class Program
{
    public static void Main()
    {
        string str = @"c#   c       python  
                    java";
 
        str = str.ReplaceWhiteSpaces();
        
        Console.WriteLine(str);
    }
}
 


 
 
  
/*
run:
 
c# c python java
 
*/

 



answered Mar 28, 2023 by avibootz
...