所以我有一个军事时间格式
的字符串:“1532”对应于下午3:32。
我正在尝试编写一种方法来检查时间字符串中的每个数字是否是适当的数字。因此第一个元素不能大于 2 或等于 0,依此类推。目前,我的代码没有运行超过第二条日志语句,我希望你们能提供帮助!
干杯!
String mOpen = "1532";
Log.d("hoursTesting","pass1, length is > 2");
if(mOpen.getText().length() == 4)
{
Log.d("hoursTesting","pass2, length is == 4");
char[] tempString = mOpen.getText().toString().toCharArray();
if(tempString[0] != 0 && tempString[0] < 3)
{
Log.d("hoursTesting","pass3, first index is != 0 and < 3");
if(tempString[0] == 1)
{
Log.d("hoursTesting","pass4, first index is 1");
if(tempString[2] <= 5)
{
Log.d("hoursTesting","pass5, third index is <= 5, success!");
}
}
else //tempString[0] is equal to 2
{
Log.d("hoursTesting","pass4, first index is 2");
if(tempString[1] < 4)
{
Log.d("hoursTesting","pass5, second index is <3");
if(tempString[2] <= 5)
{
Log.d("hoursTesting","pass6, third index is <= 5, success!");
}
}
}
}
}
最佳答案
tempString
包含字符,不包含数字。
即'0'
不是0
等等
最简单的解决方法是比较字符,例如tempString[0] == '1'
或者,您可以执行类似 int digit1 = tempString[0] - '0';
的操作- 但这种假设是假设您已经知道字符串中只有数字。
请注意那些聪明的 ASCII 家伙和他们棘手的字符集的 cos '0' < '1' < '2'
等等,所以你仍然可以说 if (str[0] < '2')
等等。您只需要小心一点,您只处理数字。
就我个人而言,我会将前 2 个字符转换为数字,将后 2 个字符转换为数字,然后仅检查 0 <= number1 <= 23 和 0 <= number2 <= 59。
关于java - 如何检查字符串中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40645083/