egyeneskanyar
egyeneskanyar

Reputation: 167

Replace strings in C#

This might be a very basic question. I need to write a code which works similar as string replace algorithm.

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;
    }

Since it's 3am the code above is probably bugged. When the new word is shorter than the old one, it goes wrong. Same as when it's longer. When the index variable is equal for both stringOld and stringNew, it will do the swap. I think... Please don't post "use string.Replace(), I have to write that algorithm myself...

Upvotes: 1

Views: 549

Answers (1)

Eli Algranti
Eli Algranti

Reputation: 9007

I don't know what you're trying to do with your code, but the problem is not a small one. Think logically about what you are trying to do. It is a two step process:

  1. Find the starting index of stringOld in s.
  2. If found replace stringOld with stringNew.

Step 1: There are many rather complex (and elegant) efficient string search algorithms, you can search for them online or look at popular 'Introduction to Algorithms' by Cormen, Leiserson, Rivest & Stein, but the naive approach involves two loops and is pretty simple. It is also described in that book (and online.)

Step 2: If a match is found at index i; simply copy characters 0 to i-1 of s to newWord, followed by newString and then the rest of the characters in s starting at index i + oldString.Length.

Upvotes: 1

Related Questions