2013-11-21 214 views
0

如何用C#中的一個空格替換字符串中的多個空格?正則表達式 - 替換空格

實施例:

PLNICI PERO 2165/HORNET SPACESPACESPACESPACESPACE 

將是:

PLNICI PERO 2165/HORNET 

其次:

實施例:

SPACESPACESPACESPACESPACE  77.000 

將是:

77.000 

請問您有什麼想法嗎?由於

+1

如果你只談論在開頭和結尾空格,然後使用String.Trim():'海峽= str.Trim();'。否則請參閱上面的重複內容.... –

+0

@OndrejJanacek它非常相似,但不包括字符串開頭和結尾的空格 – evhen14

回答

3
string input = "you  string "; 
string result = new Regex(@"[ ]+").Replace(input, " ").Trim(); 
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(); 
    } 
    } 
}