C# 如何在字符串中交替使用大小写?
我需要在一句话中交替使用这种情况,但我不知道如何使用。 例如:C# 如何在字符串中交替使用大小写?,c#,case-sensitive,C#,Case Sensitive,我需要在一句话中交替使用这种情况,但我不知道如何使用。 例如: thequickbrownfoxjumpsoverthelazydog 到 这是到目前为止我的代码 Console.WriteLine("Please enter a sentence:"); string text = Console.ReadLine(); text = text.Replace(" ", ""); char[] reversed = text.ToCharArr
thequickbrownfoxjumpsoverthelazydog
到
这是到目前为止我的代码
Console.WriteLine("Please enter a sentence:");
string text = Console.ReadLine();
text = text.Replace(" ", "");
char[] reversed = text.ToCharArray();//String to char
Array.Reverse(reversed);//Reverses char
new string(reversed);//Char to string
Console.WriteLine(reversed);
Console.ReadLine();
请注意,没有空格是有原因的,因为这也是家庭作业任务的一部分。没有必要反转字符串。字符串中的偶数索引字符只需大写 请记住,我的区域性是tr tr,此方法的工作取决于您当前的线程区域性。在本例中,您的输出可能与我的不同 这里有一个例子
字符串是不可变的,因此需要将其转换为char[]
char[] characters = text.ToCharArray();
for (int i = 0; i < characters.Length; i+=2) {
characters[i] = char.ToUpper(characters[i]);
}
text = new string(characters);
LINQ的另一个可能解决方案可以在一行中完成,如下所示:
string s = "thequickbrownfoxjumpsoverthelazydog";
string result = new String(s
// take each character
.ToCharArray()
// convert every character at even index to upper
.Select ((character, index) => (index % 2) == 0 ? Char.ToUpper(character) : character)
// back to array in order to create a string
.ToArray());
Console.WriteLine(result);
输出为:
ThEqUiCkBrOwNfOxJuMpSoVeRtHeLaZyDoG
此解决方案使用以访问当前索引和当前投影的值。一行:
new string(myString.Select((c, i) => i % 2 == 0 ? char.ToUpper(c) : c).ToArray())
扩展方法:
public static string AltCase(this string s)
{
return new string(s.Select((c, i) => i % 2 == 0 ? char.ToUpper(c) : c).ToArray());
}
你试过什么?这有点琐碎,在我们帮助您之前,您至少应该有一些代码要显示。另外,您使用什么理由来更改外壳?为什么要反转字符?还是你只是从另一个问题上复制粘贴了代码?@Selman22反转也是家庭作业的一部分task@musiclover-那为什么你的预期输出没有反转呢?交替工作,谢谢。而且,倒车也是家庭作业的一部分task@musiclover看看
ThEqUiCkBrOwNfOxJuMpSoVeRtHeLaZyDoG
new string(myString.Select((c, i) => i % 2 == 0 ? char.ToUpper(c) : c).ToArray())
public static string AltCase(this string s)
{
return new string(s.Select((c, i) => i % 2 == 0 ? char.ToUpper(c) : c).ToArray());
}