亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

如何在C#中替換字符串中的多個子字符串?

如何在C#中替換字符串中的多個子字符串?

C#
慕神8447489 2023-07-09 09:58:10
我必須替換字符串中的多個子字符串(輸入字符串的最大長度為 32)。我有一本大字典,其中可以包含數百萬個項目作為鍵值對。我需要檢查每個單詞是否存在于字典中,并替換為相應的值(如果存在于字典中)。輸入字符串可以有多個尾隨空格。該方法被調用了數百萬次,因此,它嚴重影響了性能。代碼中是否有任何優化范圍或其他更好的方法來做到這一點。public static string RandomValueCompositeField(object objInput, Dictionary<string, string> g_rawValueRandomValueMapping) {if (objInput == null)    return null;string input = objInput.ToString();if (input == "")    return input;//List<string> ls = new List<string>();int count = WhiteSpaceAtEnd(input);foreach (string data in input.Substring(0, input.Length - count).Split(' ')) {    try {        string value;        gs_dictRawValueRandomValueMapping.TryGetValue(data, out value);        if (value != null) {            //ls.Add(value.TrimEnd());            input = input.Replace(data, value);        }        else {            //ls.Add(data);        }    }    catch(Exception ex) {    }}//if (count > 0)//    input = input + new string(' ', count);    //ls.Add(new string(' ', count));return input;}編輯:我在問題中遺漏了一件重要的事情。子字符串在輸入字符串中只能出現一次。字典鍵和值具有相同數量的字符。
查看完整描述

1 回答

?
楊魅力

TA貢獻1811條經驗 獲得超6個贊

這是一個方法,它將接受輸入字符串,并通過查找“單詞”(任何連續的非空格)來構建一個新字符串,然后檢查該單詞是否在字典中,如果找到,則將其替換為相應的值。Replace這將解決“子詞”替換的問題(如果你有“hello hell”并且你想用“heaven”替換“hell”并且你不希望它給你“heaveno heaven”)。它還解決了交換問題。例如,如果您想將“yes no”中的“yes”替換為“no”,將“no”替換為“yes”,您不希望它首先將其變為“no no”,然后再變為“yes yes”。


public string ReplaceWords(string input, Dictionary<string, string> replacements)

{

    var builder = new StringBuilder();

    int wordStart = -1;

    int wordLength = 0;

    for(int i = 0; i < input.Length; i++)

    {

        // If the current character is white space check if we have a word to replace

        if(char.IsWhiteSpace(input[i]))

        {

            // If wordStart is not -1 then we have hit the end of a word

            if(wordStart >= 0)

            {

                // get the word and look it up in the dictionary

                // if found use the replacement, if not keep the word.

                var word = input.Substring(wordStart, wordLength);

                if(replacements.TryGetValue(word, out var replace))

                {

                    builder.Append(replace);

                }

                else

                {

                    builder.Append(word);

                }

            }


            // Make sure to reset the start and length

            wordStart = -1;

            wordLength = 0;


            // append whatever whitespace was found.

            builder.Append(input[i]);

        }

        // If this isn't whitespace we set wordStart if it isn't already set

        // and just increment the length.

        else

        {

            if(wordStart == -1) wordStart = i;

            wordLength++;

        }

    }


    // If wordStart is not -1 then we have a trailing word we need to check.

    if(wordStart >= 0)

    {

        var word = input.Substring(wordStart, wordLength);

        if(replacements.TryGetValue(word, out var replace))

        {

            builder.Append(replace);

        }

        else

        {

            builder.Append(word);

        }

    }


    return builder.ToString();

}


查看完整回答
反對 回復 2023-07-09
  • 1 回答
  • 0 關注
  • 281 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號