C custom string replaces Replace method instances

  • 2020-11-20 06:13:12
  • OfStack

This article is an example of the C# custom string replacement Replace method. Share to everybody for everybody reference. Specific implementation methods are as follows:

1. The question is:

1 array before encountered a problem such as the title of algorithm, are some of the pieces to replace the original string into the specified new string fragments, such as the source string: abcdeabcdfbcdefg cde replace in 12345, got the result string: ab12345abcdfb12345fg, namely: abcdeabcdfbcdefg - > ab12345abcdfb12345fg.

2. Implementation Method:

Obviously can not use string. Replace method, need to customize 1 method string Replace(string originalString, string strToBeReplaced, string strToReplace), the following is my implementation code, completed in half an hour, through debugging and general data test verification, still pass it.


public static string Replace(string originalString, string strToBeReplaced, string strToReplace)
{
    string resultString = null;
    char[] originalCharArray = originalString.ToCharArray();
    char[] strToBeCharArray = strToBeReplaced.ToCharArray();
    char[] strToCharArray = strToReplace.ToCharArray();
    List<Char> newCharList = new List<Char>();     for (int i = 0; i < originalCharArray.Count(); i++)
    {
 if (originalCharArray[i] == strToBeCharArray[0])
 {
     bool IsReplace = false;
     for (int j = 0; j < strToBeCharArray.Count(); j++)
     {
  if (((i + j) < originalCharArray.Count())
      && (originalCharArray[i + j] == strToBeCharArray[j]))
  {
      IsReplace = true;
  }
  else
  {
      IsReplace = false;
      break;
  }
     }
     if (IsReplace)
     {
  i += strToBeCharArray.Count() - 1;
  for (int k = 0; k < strToCharArray.Count(); k++)
  {
      newCharList.Add(strToCharArray[k]);
  }
     }
     else
     {
  newCharList.Add(originalCharArray[i]);
     }
 }
 else
 {
     newCharList.Add(originalCharArray[i]);
 }
    }     resultString = string.Join("", newCharList);
    return resultString;
}

Due to the time limitation, I did not add comments, but the amount of code was not large, the logic was simple and clear, and OK was not commented. The disadvantage was that the algorithm complexity was relatively high. With my consent, I reprint the implementation code of the same problem from colleague Hello Kitty, and change another way of thinking to solve the same problem. There's a little more code, a little bit more functionality, a lot of comments, but it takes a little more time. Everyone is welcome to discuss this topic with us! PS: Just now I found an bug in the following code. This is a hidden Easter egg!


public class Replace
{
        /// <summary>
        /// Replace methods
        /// </summary>
        /// <param name="source"> The original string </param>
        /// <param name="find"> The string to look for </param>
        /// <param name="replace"> Substitution string </param>
        /// <returns> Finally, replace the successful string </returns>
        public string Replace(string source, string find, string replace)
        {
            // The string to be looked for is larger than the original string , Does not process, returns the original character
            if (find.Length > source.Length)
            {
                return source;
            }             // Keep track of how many times you find it
            int findCount = 0;
            // Used for marking only, auxiliary to record how many times
            bool flag = true;
            // n : source The value of a string traversal; j : find The value of a string traversal
            int n = 0, j = 0;
            // s : Find the starting index of the string, e : Finds the end index of the string
            int s = 0, e = 0;             while (true)
            {
                // Determines if the characters are equal
                if (source[n] == find[j])
                {
                    // Source The sequence +1
                    n++;
                    // Determine if it is a control 1 A match
                    if (j == 0)
                    {
                        // Assigned to s , to find the index at the end
                        s = n;
                    }
                    // Find the bottom 1 Time to compare find Under the 1 position
                    j++;
                    // The tag temporarily finds the same character before it
                    flag = true;
                }
                else
                {
                    // The records do not match exactly
                    flag = false;
                    // find Index zeros
                    j = 0;
                    // Source The index continues to want to add
                    n++;
                }                 // The search has been completed.
                if (j == find.Length)
                {
                    // An exact match
                    if (flag)
                    {
                        // The number of characters found +1
                        findCount++;
                    }
                    // The index at the end of the array for the record lookup
                    e = n;
                    // source The index continued to +1
                    n++;
                    // find Index zeros
                    j = 0;
                    // The calculation generates a new string, and the loop continues until all strings are replaced
                    source = GetNewString(source, find, replace, s, e);
                }
                // Source Once the loop is traversed, exit the loop
                if (n >= source.Length)
                {
                    break;
                }
            }
            // Final string
            return source;
        }         /// <summary>
        /// Get the new string
        /// </summary>
        /// <param name="source"> The source string </param>
        /// <param name="find"> The character you want to look for </param>
        /// <param name="replace"> Characters that need to be replaced </param>
        /// <param name="startIndex"> The character found starts indexing </param>
        /// <param name="endIndex"> Find the character end index </param>
        /// <returns> Returns the replaced string </returns>
        public string GetNewString(string source, string find, string replace, int startIndex, int endIndex)
        {
            // The length of the new string
            int newArrayLength = source.Length + endIndex - startIndex;
            // New character array
            char[] newStringArray = new char[newArrayLength];
            // Copy the first half to the new string
            for (int i = 0; i < startIndex - 1; i++)
            {
                newStringArray[i] = source[i];
            }
            // Index is currently temporarily started
            int tempCurrentStartLength = startIndex - 1;
            // Assigns values that need to be replaced to the new character array
            for (int i = tempCurrentStartLength; i < tempCurrentStartLength + replace.Length; i++)
            {
                newStringArray[i] = replace[i - tempCurrentStartLength];
            }
            // Assigns the remaining characters to the new array
            for (int i = endIndex + 1; i < newArrayLength; i++)
            {
                newStringArray[i] = source[i - 1];
            }
            // Returns the converted string
            return string.Concat(newStringArray);
        }
}

I hope this article has been helpful for your C# programming.


Related articles: