2009-05-22 221 views
0

我有一個字符串如下;用一個字符串替換多個相同的字符

dim str as string = "this  is a string  . " 

我想識別這些多空間字符並用一個空格字符替換。使用替換函數將取代所有這些,那麼做這種任務的正確方法是什麼?

+0

欺騙。檢查出:http://stackoverflow.com/questions/206717/how-do-i-replace-multiple-spaces-with-a-single-space-in-c – 2009-05-22 14:00:50

回答

0

使用正則表達式。由該其他用戶SO的建議here

2
import System.Text.RegularExpressions    

dim str as string = "This is a  test ." 
dim r as RegEx = new Regex("[ ]+") 
str = r.Replace(str, " ") 
2

使用Regex類,以匹配「一個或多個空格」的圖案,然後用一個空格取代所有這些實例。

下面是C#代碼來做到這一點:

Regex regex = new Regex(" +"); 
string oldString = "this  is a string  . "; 
string newString = regex.Replace(oldString, " "); 
1

我會使用\ S +改性劑,這是更容易閱讀

public Regex MyRegex = new Regex(
     "\\s+", 
    RegexOptions.Multiline 
    | RegexOptions.CultureInvariant 
    | RegexOptions.Compiled 
    ); 


// This is the replacement string 
public string MyRegexReplace = " "; 

string result = MyRegex.Replace(InputText,MyRegexReplace); 

或者在VB

Public Dim MyRegex As Regex = New Regex(_ 
     "\s+", _ 
    RegexOptions.Multiline _ 
    Or RegexOptions.CultureInvariant _ 
    Or RegexOptions.Compiled _ 
    ) 


Public Dim MyRegexReplace As String = " " 


Dim result As String = MyRegex.Replace(InputText,MyRegexReplace) 
相關問題