在Android中检查字符串的长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21668632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check length of a String in Android
提问by AUJ
I want to check whether the entered strings length is between 3 to 8 characters. Previously I used if condition
and it worked. However when I introduced some substring from the string , one of the if statements
doesnt work. Can some one help me to understand why. Thanks.
我想检查输入的字符串长度是否在 3 到 8 个字符之间。以前我使用过if condition
并且有效。但是,当我从 string 中引入一些子字符串时,其中一个if statements
不起作用。有人可以帮助我理解为什么。谢谢。
My codes is
我的代码是
Working Code:
工作代码:
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");
And here, the second if statement doesnt
work.
在这里,第二个if statement doesnt
工作。
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");
回答by ErstwhileIII
You will want to ensure that you handle a null string as well as ensuring your string is within the limits you want. consider:
您需要确保处理空字符串并确保您的字符串在您想要的范围内。考虑:
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;
}
}
回答by Ted Hopp
You need to check the length before trying to create substrings, since if the length is too short the substring indexes are invalid. Try this:
您需要在尝试创建子字符串之前检查长度,因为如果长度太短,子字符串索引将无效。尝试这个:
text = et.getText().toString();
l = text.length();
if (l >= 9 || l <= 2) {
tv.setText("Invalid length!!! Please check your code");
} else {
a = text.substring(0, 1);
c = text.substring(1, 2);
d = text.substring(3, 4);
e = text.substring(4);
}
回答by Crime_Master_GoGo
You can use like this:
你可以这样使用:
editText.getText().toString().length() < 3
editText.getText().toString().length() < 3
EditText etmobile_no;
if (etmobile_no.getText().toString("") ||
etmobile_no.getText().toString().length() <3 ||
etmobile_no.getText().toString().length() >8)
{
tv.setText("Invalid length, should be from 3 to 8 characters. Please check your code");
}