Naa*_*Hai 1 c# arrays string swap
给定一个字符串,我想根据索引交换字符串中的 2 个字符。
输入:str =“你好”索引1 = 1 索引2 = 4
输出:str =“Holle”
但是当我直接尝试更新字符串字符时:
str[1] = //Assign something
Run Code Online (Sandbox Code Playgroud)
它给出了错误 ->
无法分配属性或索引器“string.this[int]”——它是只读的
所以我写了一个函数,在执行交换操作之前将字符串转换为字符数组。
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);
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,但我想知道该函数的时间复杂度是多少。我认为这是 O(n),因为 char 数组和字符串正在被构造为新的,其中 n 是传递的字符串的长度。还有其他方法可以以更好的性能执行此操作吗?
该字符串无法通过索引器赋值,因为不允许这样做。当你查一下 的定义时string,find forthis[int index]你就会知道它只允许get
交换它们的最佳方法是基于您的方法,但没有临时值。
static string SwapChars(String str, int index1, int index2)
{
char[] strChar = str.ToCharArray();
strChar[index1] = str[index2];
strChar[index2] = str[index1];
return new String(strChar);
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用Insert和Remove
static string SwapChars(String str, int index1, int index2)
{
return str.Remove(index1, 1).Insert(index1, str[index2].ToString())
.Remove(index2, 1).Insert(index2, str[index1].ToString());
}
Run Code Online (Sandbox Code Playgroud)
老实说,我更喜欢第一个,因为它很清楚。