检查Android中String的长度

时间:2014-02-10 03:27:42

标签: android string

我想检查输入的字符串长度是否在3到8个字符之间。以前我使用if condition并且它有效。但是当我从字符串中引入一些子字符串时,其中一个if statements不起作用。有人可以帮我理解原因。谢谢。

我的代码是

工作代码:

   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 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");

3 个答案:

答案 0 :(得分:7)

您需要确保处理空字符串以及确保字符串在您想要的限制范围内。考虑:

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;
    }
}

答案 1 :(得分:2)

在尝试创建子字符串之前,需要检查长度,因为如果长度太短,则子字符串索引无效。试试这个:

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);
}

答案 2 :(得分:0)

您可以这样使用:

  

editText.getText()。toString()。length()&lt; 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");
}