How to replace part of string by position?

后端 未结 18 810
逝去的感伤
逝去的感伤 2020-11-28 04:37

I have this string: ABCDEFGHIJ

I need to replace from position 4 to position 5 with the string ZX

It will look like this: ABC

相关标签:
18条回答
  • 2020-11-28 05:29

    With the help of this post, I create following function with additional length checks

    public string ReplaceStringByIndex(string original, string replaceWith, int replaceIndex)
    {
        if (original.Length >= (replaceIndex + replaceWith.Length))
        {
            StringBuilder rev = new StringBuilder(original);
            rev.Remove(replaceIndex, replaceWith.Length);
            rev.Insert(replaceIndex, replaceWith);
            return rev.ToString();
        }
        else
        {
            throw new Exception("Wrong lengths for the operation");
        }
    }
    
    0 讨论(0)
  • Here is a simple extension method:

        public static class StringBuilderExtensions
        {
            public static StringBuilder Replace(this StringBuilder sb, int position, string newString)
                => sb.Replace(position, newString.Length, newString);
    
            public static StringBuilder Replace(this StringBuilder sb, int position, int length, string newString)
                => (newString.Length <= length)
                    ? sb.Remove(position, newString.Length).Insert(position, newString)
                    : sb.Remove(position, length).Insert(position, newString.Substring(0, length));
        }
    

    Use it like this:

    var theString = new string(' ', 10);
    var sb = new StringBuilder(theString);
    sb.Replace(5, "foo");
    return sb.ToString();
    
    0 讨论(0)
  • 2020-11-28 05:31

    All others answers don't work if the string contains Unicode char (like Emojis) because an Unicode char weight more bytes than a char.

    Example : the emoji '

    0 讨论(0)
  • 2020-11-28 05:32

    It's better to use the String.substr().

    Like this:

    ReplString = GivenStr.substr(0, PostostarRelStr)
               + GivenStr(PostostarRelStr, ReplString.lenght());
    
    0 讨论(0)
  • 2020-11-28 05:34

    As an extension method.

    public static class StringBuilderExtension
    {
        public static string SubsituteString(this string OriginalStr, int index, int length, string SubsituteStr)
        {
            return new StringBuilder(OriginalStr).Remove(index, length).Insert(index, SubsituteStr).ToString();
        }
    }
    
    0 讨论(0)
  • 2020-11-28 05:36

    Yet another

        public static string ReplaceAtPosition(this string self, int position, string newValue)        
        {
            return self.Remove(position, newValue.Length).Insert(position, newValue); 
        }
    
    0 讨论(0)
提交回复
热议问题