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.