第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有String.Replace的方法只打了“整個單詞”

有String.Replace的方法只打了“整個單詞”

烙印99 2019-08-28 09:27:33
有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" ) );


查看完整回答
反對 回復 2019-08-28
  • 3 回答
  • 0 關注
  • 572 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號