0

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

Example:

PLNICI PERO 2165/HORNET SPACESPACESPACESPACESPACE

would be:

PLNICI PERO 2165/HORNET

And second:

Example:

SPACESPACESPACESPACESPACE      77.000

would be:

77.000

Have you any idea please? Thanks

Kate
  • 372
  • 2
  • 11
  • 24
  • 1
    If you're only talking spaces at the beginning and end, then use String.Trim(): `str = str.Trim();`. Otherwise see the duplicates above.... – Idle_Mind Nov 21 '13 at 06:24
  • @OndrejJanacek It's very similar, but doesn't cover spaces in the beginning and end of string – evhen14 Nov 21 '13 at 06:36

2 Answers2

3
string input = "you     string    ";
string result = new Regex(@"[ ]+").Replace(input, " ").Trim();
evhen14
  • 1,839
  • 12
  • 16
1
using System;
using System.Text;
using System.Text.RegularExpressions;   // for Regex

namespace tentitive
{   
 class Program
 {
    static void Main(string[] args)
     { 
       string firstString = "PLNICI PERO 2165/HORNET                           ";
       string secondString = "              77.000"; 
       string toBeReplaced = "[ ]+";    // pattern to be replaced i.e. one or more occurences of   white spaces
       string replacer = " ";           // has to be replaced with only One white space 
       string neededFirstString = Regex.Replace(firstString, toBeReplaced, replacer).ToString();
       string neededSecondString = Regex.Replace(secondString, toBeReplaced, replacer).ToString();
       Console.WriteLine(neededFirstString);
       Console.WriteLine(neededSecondString);
       Console.ReadLine();
     }
  }
}
manish
  • 1,450
  • 8
  • 13