2012-09-05 23 views
1

可以說我有串這樣的,去掉空格,如果兩個以上的空間不斷存在

String sample = "This is a sample string with more than two spaces in  a string "; 

現在我需要做的,使字符串只有一個每個單詞之間的空格。 在此先感謝。

+2

可能重複的[Java正則表達式 - 減少字符串中的空格](http://stackoverflow.com/questions/575500/java-regex-reduce-spaces-in-a-string) – deceze

回答

8

如果字面意思是「空間」,那麼你可以用一個空格替換/ {2,}/。請注意,正則表達式中的空格與文本中的空格相匹配。

如果用「空格」表示實際上是指「所有空格」(空格,製表符,換行符等),則改爲使用\s+

3

\s+正則表達式匹配他們和單個空格代替.. 如果你只想要替換多個空格(而不是製表符等白色字符)使用\ +

1

如果這是C#,那麼你可以做

using System.Text.RegularExpressions; 
… 
     String sample = "This is a sample string with more than two spaces in  a string "; 
     sample = Regex.Replace(sample, @"\s+", " ");