检查Android中String的长度

AUJ*_*AUJ 6 string android

我想检查输入的字符串长度是否在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");
Run Code Online (Sandbox Code Playgroud)

在这里,第二项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");
Run Code Online (Sandbox Code Playgroud)

Ers*_*III 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;
    }
}
Run Code Online (Sandbox Code Playgroud)