有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条经验 获得超18个赞
正如Sga评论的那样,正则表达式解决方案并不完美。我猜也不会表现友好。
这是我的贡献:
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 关注
- 548 浏览
添加回答
举报
0/150
提交
取消