在C#中字符串的所有字母相反的情况 [英] Reverse case of all alphabetic characters in C# string
问题描述
什么是扭转在C#字符串中的所有字母的情况下,最简单的方法是什么?例如,ABC1 $;应该成为ABC1 $;我可以很容易地编写,这是否一种方法,但我希望有一个库调用,我不知道,这将使这更容易。我也想避免的所有已知的字母字符的列表和每个字符进行比较的是什么在列表中。也许这可以用正则表达式来完成,但我不知道他们很好。谢谢你。
感谢您的帮助。我创建了一个字符串的扩展方法,这一点,主要是由安东尼Pegram的解决方案的启发,但没有LINQ。我觉得这个罢工的可读性和性能之间的良好平衡。以下是我想出了。
公共静态字符串的swapCase(此字符串源){
的char [] caseSwappedChars =新的char [source.Length]
的for(int i = 0; I< caseSwappedChars.Length;我++){
焦炭C =源[I]
如果(char.IsLetter(c))的{
caseSwappedChars由[i] =
char.IsUpper(三)? char.ToLower(C):char.ToUpper(C);
}其他{
caseSwappedChars [i] = C;
}
}
返回新的字符串(caseSwappedChars);
}
您能做到这一点的使用LINQ线。一种方法:
字符串输入=ABC1 $;
串reversedCase =新的字符串(
input.Select(C => char.IsLetter(C)(char.IsUpper(C)
char.ToLower(三):??字符。 ToUpper的(c))的:三).ToArray());
What is the simplest way to reverse the case of all alphabetic characters in a C# string? For example "aBc1$;" should become "AbC1$;" I could easily write a method that does this, but I am hoping there is a library call that I don't know about that would make this easier. I would also like to avoid having a list of all known alphabetic characters and comparing each character to what is in the list. Maybe this can be done with regular expressions, but I don't know them very well. Thanks.
Thanks for the help. I created a string extension method for this that is mostly inspired by Anthony Pegram's solution, but without the LINQ. I think this strikes a good balance between readability and performance. Here is what I came up with.
public static string SwapCase(this string source) {
char[] caseSwappedChars = new char[source.Length];
for(int i = 0; i < caseSwappedChars.Length; i++) {
char c = source[i];
if(char.IsLetter(c)) {
caseSwappedChars[i] =
char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
} else {
caseSwappedChars[i] = c;
}
}
return new string(caseSwappedChars);
}
You could do it in a line with LINQ. One method:
string input = "aBc1$";
string reversedCase = new string(
input.Select(c => char.IsLetter(c) ? (char.IsUpper(c) ?
char.ToLower(c) : char.ToUpper(c)) : c).ToArray());
这篇关于在C#中字符串的所有字母相反的情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!