检查字符串中的所有字母是否都是大写的递归 [英] Check if all the letters in a string are capital recursively
问题描述
我必须检查递归中的所有字母是否都是大写字母,但我不知道为什么这不起作用:
I have to check if all the letters are capital letters in recursion, and i dont know why this isnt working:
public static bool IsCapital(string str)
{
if (str.Length == 1)
return int.Parse(str[0].ToString()) > 65 && int.Parse(str[0].ToString()) < 90;
return IsCapital(str.Substring(1)) && int.Parse(str[0].ToString()) > 65 && int.Parse(str[0].ToString()) < 90;
}
它崩溃并说:未处理的异常:System.FormatException:输入字符串的格式不正确."
It crashes and says: "Unhandled exception: System.FormatException: Input string was not in a correct format."
Console.WriteLine(IsCapital("abc"));
谢谢.
推荐答案
为了单独解决异常,不要解析字符串.您可以直接将 char
与任何 ushort
值进行比较.
To solely address the exception, just don't parse strings. You can directly compare a char
to any ushort
value.
换句话说,这是一个有效的检查(没有字符串解析)
In other words, this is a valid check (without string parsing)
str[0] > 65
AsciiTable.com 应该会告诉您为什么您的检查会在边缘失败.
AsciiTable.com should show you why the checks you have will fail on the edges.
还要考虑...
- 不是字母的字符.
IsCapital(null)
最后,可能使这更容易的事情(假设非字母被绕过)是沿着 bool IsNotLowerCase(char c)
的行创建一个方法.
Finally, something that might make this easier (assuming non-letters get bypassed) is to create a method along the lines of bool IsNotLowerCase(char c)
.
注意——这些都假设为 ASCII,从我的链接中可以看出.
Note -- these are all assuming ASCII, as evident by my link.
如果您必须支持完整的 Unicode,希望您可以使用 char
的方法.
If you must support full Unicode, hopefully you can use the methods of char
.
这篇关于检查字符串中的所有字母是否都是大写的递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!