How to convert multiple whitespaces to single space in C#

1 Answer

0 votes
using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            string s1 = "c# \n            java";
            s1 = WhitespacesToSingleSpace(s1);
            Console.WriteLine(s1);

            string s2 = "c\r\n                       c++";
            s2 = WhitespacesToSingleSpace(s2);
            Console.WriteLine(s2);
        }

        public static string WhitespacesToSingleSpace(string str)
        {
            str = Regex.Replace(str, @"\s+", " ");

            return str;
        }
    }
}


/*
run:

c# java
c c++

*/

 



answered Jan 4, 2017 by avibootz
edited Jan 4, 2017 by avibootz
...