我想检查输入的字符串长度是否在 3 到 8 个字符之间。以前我使用 if condition
并且它有效。但是,当我从字符串中引入一些子字符串时,其中一个 if 语句
不起作用。有人可以帮助我理解为什么。谢谢。
我的代码是
工作代码:
text = et.getText().toString();
l = text.length();
a = text.substring(0, 1);
if (l >=9) tv.setText("Invalid length!!! Please check your code");
if (l <= 2) tv.setText("Invalid length! Please check your code");
在这里,第二个 if 语句不起作用
。
text = et.getText().toString();
l = text.length();
a = text.substring(0, 1);
c = text.substring(1, 2);
d = text.substring(3, 4);
e = text.substring(4);
if (l >=9) tv.setText("Invalid length!!! Please check your code");
if (l <= 2) tv.setText("Invalid length! Please check your code");
最佳答案
您需要确保处理空字符串并确保您的字符串在您想要的限制范围内。考虑:
text = et.getText().toString();
if (text == null || text.length() < 3 || text.length > 8) {
tv.setText("Invalid length, should be from 3 to 8 characters. Please check your code");
} else {
a = text.substring(0,1);
b = text.substring(1,2);
c = text.substring(3,4);
if (text.length() > 3) {
d = text.substring(4);
} else {
d = null;
}
}
关于android - 检查Android中字符串的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21668632/