android - 检查Android中字符串的长度

标签 android string

我想检查输入的字符串长度是否在 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/

相关文章:

c# - Codedom 和字符串处理

string - 如何从 shell 字符串中删除最后一个字段

r - 如何获取每个字符串 r 中以某些字符结尾的单词

java.util.regex.PatternSyntaxException : at\b within regexp

android - xamarin android MVVMCross click按钮分配textview

android - 带有 java.lang.reflect.InvocationTargetException 的 android 上的 JAIN SIP

java - 如何在android中的共享首选项中使用主键?

sql - 在没有 JSON_VALUE 的 SQL 中获取 json 值

c++ - 当访问要插入 union vector 中的字符串字符时, vector 中的字符串会变得困惑

Android Firebase 等待数据