Search code examples
c#arraysstringswap

swap 2 characters in the string based on their indices


Given a string I want to swap 2 characters in the string based on their indices.

Input : str = "Hello" index1 = 1 index2 = 4

Output : str = "Holle"

but when I directly try updating the string character :

str[1] = //Assign something 

it gives the error ->

Property or indexer 'string.this[int]' cannot be assigned to -- it is read only

So I wrote a function that converts the string to character array before performing the swap operation.

static string SwapChars(String str, int index1, int index2)
{
    char[] strChar = str.ToCharArray();
    char temp = strChar[index1];
    strChar[index1] = strChar[index2];
    strChar[index2] = temp;
    
    return new String(strChar);
}

It is working fine, but I want to know what is the time complexity for the function. I think it is O(n) as char array and string are getting constructed as new, where n is length of string passed. Also is there some other way I can perform this operation with better performance.


Solution

  • You could use pointers, with minimal allocations

    public unsafe void SwapChars(ref string str, int index1, int index2)
    {
       fixed (char* p = str)
       {
          var temp = p[index1];
          p[index1] = p[index2];
          p[index2] = temp;
       }
    }
    

    Note the above is fairly dangerous, as it will mess-up unturned strings

    This would be safer

    public static unsafe string SwapChars(string str, int index1, int index2)
    {
       if (str == null) throw new ArgumentNullException(nameof(str));
       if (index1 < 0 || index1 >= str.Length) throw new ArgumentOutOfRangeException(nameof(index1));
       if (index2 < 0 || index2 >= str.Length) throw new ArgumentOutOfRangeException(nameof(index1));
    
       var result = new string(str);
    
       fixed (char* p = result)
       {
          var temp = p[index1];
          p[index1] = p[index2];
          p[index2] = temp;
       }
       return result;
    }