How to replace part of string by position?

后端 未结 18 808
逝去的感伤
逝去的感伤 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:10

    ReplaceAt(int index, int length, string replace)

    Here's an extension method that doesn't use StringBuilder or Substring. This method also allows the replacement string to extend past the length of the source string.

    //// str - the source string
    //// index- the start location to replace at (0-based)
    //// length - the number of characters to be removed before inserting
    //// replace - the string that is replacing characters
    public static string ReplaceAt(this string str, int index, int length, string replace)
    {
        return str.Remove(index, Math.Min(length, str.Length - index))
                .Insert(index, replace);
    }
    

    When using this function, if you want the entire replacement string to replace as many characters as possible, then set length to the length of the replacement string:

    "0123456789".ReplaceAt(7, 5, "Hello") = "0123456Hello"
    

    Otherwise, you can specify the amount of characters that will be removed:

    "0123456789".ReplaceAt(2, 2, "Hello") = "01Hello456789"
    

    If you specify the length to be 0, then this function acts just like the insert function:

    "0123456789".ReplaceAt(4, 0, "Hello") = "0123Hello456789"
    

    I guess this is more efficient since the StringBuilder class need not be initialized and since it uses more basic operations. Please correct me if I am wrong. :)

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

    Like other have mentioned the Substring() function is there for a reason:

    static void Main(string[] args)
    {
        string input = "ABCDEFGHIJ";
    
        string output = input.Overwrite(3, "ZX"); // 4th position has index 3
        // ABCZXFGHIJ
    }
    
    public static string Overwrite(this string text, int position, string new_text)
    {
        return text.Substring(0, position) + new_text + text.Substring(position + new_text.Length);
    }
    

    Also I timed this against the StringBuilder solution and got 900 tics vs. 875. So it is slightly slower.

    0 讨论(0)
  • 2020-11-28 05:13
    string s = "ABCDEFGH";
    s= s.Remove(3, 2).Insert(3, "ZX");
    
    0 讨论(0)
  • 2020-11-28 05:13

    If you care about performance, then the thing you want to avoid here are allocations. And if you're on .Net Core 2.1+ (or the, as yet unreleased, .Net Standard 2.1), then you can, by using the string.Create method:

    public static string ReplaceAt(this string str, int index, int length, string replace)
    {
        return string.Create(str.Length - length + replace.Length, (str, index, length, replace),
            (span, state) =>
            {
                state.str.AsSpan().Slice(0, state.index).CopyTo(span);
                state.replace.AsSpan().CopyTo(span.Slice(state.index));
                state.str.AsSpan().Slice(state.index + state.length).CopyTo(span.Slice(state.index + state.replace.Length));
            });
    }
    

    This approach is harder to understand than the alternatives, but it's the only one that will allocate only one object per call: the newly created string.

    0 讨论(0)
  • 2020-11-28 05:13
    String timestamp = "2019-09-18 21.42.05.000705";
    String sub1 = timestamp.substring(0, 19).replace('.', ':'); 
    String sub2 = timestamp.substring(19, timestamp.length());
    System.out.println("Original String "+ timestamp);      
    System.out.println("Replaced Value "+ sub1+sub2);
    
    0 讨论(0)
  • 2020-11-28 05:21

    I believe the simplest way would be this:(without stringbuilder)

    string myString = "ABCDEFGHIJ";
    char[] replacementChars = {'Z', 'X'};
    byte j = 0;
    
    for (byte i = 3; i <= 4; i++, j++)  
    {                   
    myString = myString.Replace(myString[i], replacementChars[j]);  
    }
    

    This works because a variable of type string can be treated as an array of char variables. You can, for example refer to the second character of a string variable with name "myString" as myString[1]

    0 讨论(0)
提交回复
热议问题