【发布时间】:2020-10-14 12:33:54
【问题描述】:
伙计们!我有这种情况:给定一个字符串和另外两个字符 X 和 Y。将所有 X 字符移到字符串的开头,将所有 Y 字符移到字符串的末尾。字符串中其他字符的顺序保持不变。 我写了两个函数 MoveCharsLeft 和 MoveCharsRight 将 X 向左移动和 Y 向右移动,但是有一个错误 System.IndexOutOfRangeException: 'Index was outside the数组的边界。' 在这行代码 char toReplace = splitText[charToCheck]; 我不知道如何处理它,以解决练习。 各位大神能帮我看看,功能应该是怎样的?
static void Main()
{
string text = Console.ReadLine();
char[] splitText = text.ToCharArray();
string firstLetter = Console.ReadLine();
char[] firstChar = firstLetter.ToCharArray();
string secondLetter = Console.ReadLine();
char[] secondChar = secondLetter.ToCharArray();
char one = firstChar[0];
char two = secondChar[0];
Console.WriteLine(CheckChars(splitText, one, two));
Console.ReadLine();
}
static char[] CheckChars(char[] splitText, char one, char two)
{
for (char letter = 'a'; letter <= 'z'; letter++)
{
if (Array.IndexOf(splitText, one) > -1)
{
MoveCharsLeft(splitText, one);
}
if (Array.IndexOf(splitText, two) > -1)
{
MoveCharsRight(splitText, two);
}
}
return splitText;
}
static void MoveCharsLeft(char[] splitText, char charToCheck)
{
char toReplace = splitText[charToCheck];
char currentLetter = splitText[0];
for (int i = 0; i <= charToCheck; i++)
{
char temporary = splitText[i];
splitText[i] = currentLetter;
currentLetter = temporary;
}
splitText[0] = toReplace;
}
static void MoveCharsRight(char[] splitText, char charToCheck)
{
char toReplace = splitText[charToCheck];
char currentLetter = splitText[-1];
for (int i = 0; i <= charToCheck; i++)
{
char temporary = splitText[i];
splitText[i] = currentLetter;
currentLetter = temporary;
}
splitText[-1] = toReplace;
}
【问题讨论】:
标签: c# arrays string char swap