首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Android -检查字符串的内容

Android -检查字符串的内容
EN

Stack Overflow用户
提问于 2014-02-10 12:01:17
回答 3查看 200关注 0票数 0

我将一个字符串(长度为3-8)分配给一个变量(text)。我想检查第二个和第三个字符是否不是数字(字母或符号或space..or数字以外的任何东西)。

EN

回答 3

Stack Overflow用户

发布于 2014-02-10 12:10:53

基本的方法可能是:

代码语言:javascript
运行
复制
if(((text.charAt(1)-'0')>=0)&&(text.charAt(1)-'0')<10))||((text.charAt(2)-'0')>=0)&&(text.charAt(2)-'0')<10)))
{
   //do nothing, since this means 2nd and/or 3rd characters in the string are numeric
}
else
{
                // Your condition is met
}

如果你的检查仍然很复杂,你也可以使用REGEX。

票数 0
EN

Stack Overflow用户

发布于 2014-02-10 12:12:01

这是另一种实现这一点的方法:

代码语言:javascript
运行
复制
    boolean isNumeric = true;
    String test = "testing";
    char second = test.charAt(1);
    char third = test.charAt(2);

    try {
        Integer.parseInt(String.valueOf(second));
        Integer.parseInt(String.valueOf(third));
    } catch(NumberFormatException e) {
        isNumeric = false;
    }
    System.out.println("Contains Number in 2nd and 3rd or both position: " + isNumeric);
票数 0
EN

Stack Overflow用户

发布于 2014-02-10 12:16:19

您可以使用String.IndexOf(String)方法,如下所示:

代码语言:javascript
运行
复制
    String digits = "0123456789";
String s2 = text.substring(2,3);
String s3 = text.substring(3,4);
boolean valid = (digits.indexOf(s2) > -1) && (digits.indexOf(s3) > -1);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21668875

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档