英文:
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 = '0'; num <= '9'; 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(".*\\d+.*") ? "yes" : "no";
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论