如何检查字符串中是否包含任何数字?

huangapple go评论69阅读模式
英文:

How do I check to see if a string has any numbers?

问题

String go(String a) {
    int x = a.indexOf("0");
    if (x == -1) {
        return "no";
    } else {
        return "yes";
    }
}
英文:

So I am supposed to create a method which checks to see if a string contains any numbers. It will return "yes" if it does and "no" if it does not. I think I have done everything correct so far, but am not sure how to use the indexOf() to search for any number ranging from 0 - 9. Please note I am a beginner in javascript, so I would appreciate beginner friendly responses.

String go( String a  ) 
{
    int x = a.indexOf( ??? );
    {
      if (x == -1)
      {
        return "no";
      }
      else
      {
        return "yes";
      }
    }
}

答案1

得分: 1

你可以使用以下正则表达式与字符串 s1 进行匹配,该正则表达式检查字符串中是否有一个或多个数字。

boolean hasDigit = s1.matches(".*\\d+.*");
英文:

You can match your string s1 with this regex which checks if there is one or more digits in the string.

boolean hasDigit = s1.matches(".*\\d+.*");

答案2

得分: 0

C++中有一个非常适合搜索任意几个指定字符的函数,而在Java中,必须逐个检查每个字符。

如果您希望改为使用indexOf,请注意,如果字符不存在,它会返回-1。您走在正确的轨道上,但需要逐个搜索它们。

Java代码:

~~~

public boolean hasNum(String s) {
  for(char num = '0'; num <= '9'; num=num+1) {
    if(s.indexOf(num) != -1) return true;
  }
  return false; //没有发现任何一个字符,所以执行到这里
}

~~~
英文:

While C++ has a function that's quite suitable for searching for any of several specified chars, in java one must check for each char.

https://stackoverflow.com/questions/17370312/java-equivalent-for-cs-stdstringfind-first-of

If you wish to instead use indexOf, note that it returns -1 if char is not present. You are on the right track, but need to search for each of them.

java:


public boolean hasNum(String s) {
  for(char num = &#39;0&#39;; num &lt;= &#39;9&#39;; num=num+1) {
    if(s.indexOf(num) != -1) return true;
  }
  return false; //none of them were found so we got here
}

答案3

得分: 0

public String checkNumbers(String text) {
    return text.matches(".*\\d+.*") ? "yes" : "no";
}
英文:
    public String checkNumbers(String text) {
    return text.matches(&quot;.*\\d+.*&quot;) ? &quot;yes&quot; : &quot;no&quot;;
}

huangapple
  • 本文由 发表于 2020年9月17日 02:01:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63925590.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定