En  Fa
softprojects.org
Discovering: Tips & Tricks  > Languages  > C# Tips  > Fast string replacing algorithm with C# in dotNET
 

Articles

 

 

Tips and Tricks

 


 

Fast string replacing algorithm with C# in dotNET

Print version  

Fast string replacing algorithm with C# in dotNET

Description

This function uses a fast replacing algorithm which is written for C#. This function is suitable choice for replace operations with long strings.

C# Code

/// <summary>
/// Implements fast string replacing algorithm for CS
/// </summary>
public static string ReplaceEx(string original, string pattern, string replacement, StringComparison comparisonType)
{
    if (original == null)
    {
        return null;
    }

    if (String.IsNullOrEmpty(pattern))
    {
        return original;
    }

    int lenPattern = pattern.Length;
    int idxPattern = -1;
    int idxLast = 0;

    StringBuilder result = new StringBuilder();

    while (true)
    {
        idxPattern = original.IndexOf(pattern, idxPattern + 1, comparisonType);

        if (idxPattern < 0)
        {
            result.Append(original, idxLast, original.Length - idxLast);

            break;
        }

        result.Append(original, idxLast, idxPattern - idxLast);
        result.Append(replacement);

        idxLast = idxPattern + lenPattern;
    }

    return result.ToString();
}

Details
      
Writer: Salar Khalilzadeh
Date Sent: 3/28/2008 5:20 PM
Views: 302
Votes: 2
Rating: 4.50 Points from 4.50 Points

Your Rating:
bookmark this
 

There is no comment for this topic.

Language:

Copyright © 2008 SoftProjects.org | About | Valid XHTML | CSS