0

何度か操作している stringbuilder があり、その中の文字列をさまざまな長さの文字列に置き換える必要があります。

sb = new StringBuilder("This has {Count} Values.  Your search was '{SearchText}'.  Did you mean '{DidYouMean}'?")
//get the replacement areas, this would search for the field names within {}
MatchCollection matches = GetReplacementAreas(sb);

int indexOffset=0;
foreach(Match m in matches)
{
   //fields is a dictionary containing keys that match the fields
   sb.ReplaceAt(m.Index,m.Length,fields[m.Value]); 
}

明らかに、ReplaceAt は存在​​しません。私はそれを自分で書くつもりです。他の誰かがすでにそうしていますか?

4

2 に答える 2

0
public static class StringBuilderExtensions
{
#if EXTENSIONS_SUPPORTED
    public static StringBuilder ReplaceAt(this StringBuilder sb, string value, int index, int count)
    {
        return StringBuilderExtensions.ReplaceAt(sb, value, index, count);
    }
#endif

    public static StringBuilder ReplaceAt(StringBuilder sb, string value, int index, int count)
    {
        if (value == null)
        {
            sb.Remove(index, count);
        }
        else
        {
            int lengthOfValue = value.Length;

            if (lengthOfValue > count)
            {
                string valueToInsert = value.Substring(count);
                sb.Insert(index + count, valueToInsert);
            }
            if (lengthOfValue < count)
            {
                sb.Remove(index + count, lengthOfValue - count);
            }

            char[] valueChars = value.ToCharArray();
            for (int i = 0; i < lengthOfValue; i++)
            {
                sb[index + i] = valueChars[i];
            }
        }

        return sb;
    }
}
于 2012-08-06T15:27:36.543 に答える