有String.Replace的方法只打了“整個單詞”我需要一種方法來做到這一點:"test, and test but not testing. But yes to test".Replace("test", "text")歸還這個:"text, and text but not testing. But yes to text"基本上我想替換整個單詞,但不是部分匹配。注意:我將不得不使用VB(SSRS 2008代碼),但C#是我的正常語言,因此兩者中的響應都很好。
3 回答

慕容森
TA貢獻1853條經(jīng)驗 獲得超18個贊
正如Sga評論的那樣,正則表達式解決方案并不完美。我猜也不會表現(xiàn)友好。
這是我的貢獻:
public static class StringExtendsionsMethods{ public static String ReplaceWholeWord ( this String s, String word, String bywhat ) { char firstLetter = word[0]; StringBuilder sb = new StringBuilder(); bool previousWasLetterOrDigit = false; int i = 0; while ( i < s.Length - word.Length + 1 ) { bool wordFound = false; char c = s[i]; if ( c == firstLetter ) if ( ! previousWasLetterOrDigit ) if ( s.Substring ( i, word.Length ).Equals ( word ) ) { wordFound = true; bool wholeWordFound = true; if ( s.Length > i + word.Length ) { if ( Char.IsLetterOrDigit ( s[i+word.Length] ) ) wholeWordFound = false; } if ( wholeWordFound ) sb.Append ( bywhat ); else sb.Append ( word ); i += word.Length; } if ( ! wordFound ) { previousWasLetterOrDigit = Char.IsLetterOrDigit ( c ); sb.Append ( c ); i++; } } if ( s.Length - i > 0 ) sb.Append ( s.Substring ( i ) ); return sb.ToString (); }}
...對于測試用例:
String a = "alpha is alpha";Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "alphonse" ) );Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "alf" ) );a = "alphaisomega";Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "xxx" ) );a = "aalpha is alphaa";Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "xxx" ) );a = "alpha1/alpha2/alpha3";Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "xxx" ) );a = "alpha/alpha/alpha";Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "alphonse" ) );
- 3 回答
- 0 關注
- 572 瀏覽
添加回答
舉報
0/150
提交
取消