How to replace part of string by position?

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

    string myString = "ABCDEFGHIJ";
    string modifiedString = new StringBuilder(myString){[3]='Z', [4]='X'}.ToString();
    

    Let me explain my solution.
    Given the problem statement of altering a string in its two specific position (“position 4 to position 5”) with two character ‘Z’ and ‘X’ and the ask is to use the position index to alter the string and not string Replace() method(may be because of the possibility of repetition of some characters in the actual string), I would prefer to use minimalist approach to achieve the goal over using Substring() and string Concat() or string Remove() and Insert() approach. Though all those solutions will serve the purpose in attaining the same goal, but it just depends on personal choice and philosophy of settling with minimalist approach.
    Coming back to my solution mention above, if we take a closer look of string and StringBuilder, both of them internally treats a given string as an array of characters. If we look at the implementation of StringBuilder it maintains an internal variable something like “internal char[] m_ChunkChars;” to capture the given string. Now since this is an internal variable, we cannot directly access the same. For external world, to be able to access and alter that character array, StringBuilder exposes them through indexer property which looks something like below

        [IndexerName("Chars")]
        public char this[int index]
        {
          get
          {
            StringBuilder stringBuilder = this;
            do
            {
              // … some code
                return stringBuilder.m_ChunkChars[index1];
              // … some more code
            }
          }
          set
          {
            StringBuilder stringBuilder = this;
            do
            {
                //… some code
                stringBuilder.m_ChunkChars[index1] = value;
                return;
                // …. Some more code
            }
          }
        }
    

    My solution mentioned above leverage this indexer capability to directly alter the internally maintained character array which IMO is efficient and minimalist.

    BTW; we can rewrite the above solution more elaborately something like below

     string myString = "ABCDEFGHIJ";
     StringBuilder tempString = new StringBuilder(myString);
     tempString[3] = 'Z';
     tempString[4] = 'X';
     string modifiedString = tempString.ToString();
    

    In this context also would like to mention that in case of string it also have indexer property as a means to expose its internal character array, but in this case it only has Getter property (and no Setter) as string is immutable in nature. And that is why we need to use StringBuilder to alter the character array.

    [IndexerName("Chars")]
    public extern char this[int index] { [SecuritySafeCritical, __DynamicallyInvokable, MethodImpl(MethodImplOptions.InternalCall)] get; }
    

    And last but not the least this solution is only best fit for this specific problem where the ask is to replace only few characters with a known position index upfront. It may not be the best fit when the requirement is to alter a fairly lengthy string i.e. number of characters to alter are large in numbers.

提交回复
热议问题