替换C#中的字符串

时间:2013-10-15 00:56:36

标签: c# string algorithm replace

这可能是一个非常基本的问题。我需要编写一个与字符串替换算法类似的代码。

static string stringReplace(string s, string stringOld, string stringNew)
    {
        string newWord = "";
        int oldMax = stringOld.Length;
        int index = 0;
        for (int i = 0; i < s.Length; i++)
        {
            if (index != oldMax && s[i] == stringOld[index])
            {
                if (stringOld[index] < stringNew[index])
                {
                    newWord = newWord + stringNew[index];
                    index++;
                }
                else
                {
                    newWord = newWord + stringNew[index];
                }
            }
            else
            {
                newWord = newWord + s[i];
            }
        }
        return newWord;
    }

由于凌晨3点,上面的代码可能会被窃听。当新单词比旧单词短时,就会出错。与更长时间相同。当stringOld和stringNew的索引变量相等时,它将进行交换。我想......请不要发布“使用string.Replace(),我必须自己编写该算法......

1 个答案:

答案 0 :(得分:1)

我不知道你要对你的代码做什么,但问题不是很小。 从逻辑上思考你想要做什么。 这是一个两步过程:

  1. 在s。中找到stringOld的起始索引。
  2. 如果找到,请用stringNew替换stringOld。
  3. 第1步: 有许多相当复杂(优雅)的高效字符串搜索算法,您可以在线搜索它们或查看Cormen,Leiserson,Rivest&amp;斯坦因,但天真的方法涉及两个循环,非常简单。它也在那本书(和在线)中有描述。

    第2步: 如果在索引i处找到匹配项;只需将0的{​​{1}}字符复制到i-1,然后复制s,然后将newWord中的其余字符复制到索引处newString