Jon*_*Jon 79
看isDigit(char ch)
方法:
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Character.html
并使用该String.charAt()
方法将其传递给String的第一个字符.
Character.isDigit(myString.charAt(0));
Run Code Online (Sandbox Code Playgroud)
Bro*_*olf 18
抱歉,我没有看到你的Java标签,只是在阅读问题.因为我把它们打印出来,所以我会在这里留下我的其他答案.
Java的
String myString = "9Hello World!";
if ( Character.isDigit(myString.charAt(0)) )
{
System.out.println("String begins with a digit");
}
Run Code Online (Sandbox Code Playgroud)
C++:
string myString = "2Hello World!";
if (isdigit( myString[0]) )
{
printf("String begins with a digit");
}
Run Code Online (Sandbox Code Playgroud)
正则表达式:
\b[0-9]
Run Code Online (Sandbox Code Playgroud)
一些证明我的正则表达式有效:除非我的测试数据错误? 替代文字http://i29.tinypic.com/15z5pw8.png
Tom*_*Tom 11
我认为你应该使用正则表达式:
import java.util.regex.*;
public class Test {
public static void main(String[] args) {
String neg = "-123abc";
String pos = "123abc";
String non = "abc123";
/* I'm not sure if this regex is too verbose, but it should be
* clear. It checks that the string starts with either a series
* of one or more digits... OR a negative sign followed by 1 or
* more digits. Anything can follow the digits. Update as you need
* for things that should not follow the digits or for floating
* point numbers.
*/
Pattern pattern = Pattern.compile("^(\\d+.*|-\\d+.*)");
Matcher matcher = pattern.matcher(neg);
if(matcher.matches()) {
System.out.println("matches negative number");
}
matcher = pattern.matcher(pos);
if (matcher.matches()) {
System.out.println("positive matches");
}
matcher = pattern.matcher(non);
if (!matcher.matches()) {
System.out.println("letters don't match :-)!!!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可能希望调整此值以接受浮点数,但这将适用于负数.其他答案不适用于否定因为他们只检查第一个字符!更具体地说明您的需求,我可以帮助您调整此方法.
这应该工作:
String s = "123foo";
Character.isDigit(s.charAt(0));
Run Code Online (Sandbox Code Playgroud)