我有一个包含字母数字字符的字符串。
我需要检查这个字符串是否以数字开头。
谢谢,
我有一个包含字母数字字符的字符串。
我需要检查这个字符串是否以数字开头。
谢谢,
查看isDigit(char ch)
方法:
https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Character.html
并使用String.charAt()
方法将其传递给字符串的第一个字符。
Character.isDigit(myString.charAt(0));
抱歉我没有注意到你的Java标签,只看了问题。不过我还是会把其他回答保留在这里,因为我已经打出来了。
Java
String myString = "9Hello World!";
if ( Character.isDigit(myString.charAt(0)) )
{
System.out.println("String begins with a digit");
}
C++:
string myString = "2Hello World!";
if (isdigit( myString[0]) )
{
printf("String begins with a digit");
}
正则表达式:
\b[0-9]
我认为你应该使用正则表达式:
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 :-)!!!");
}
}
}
String s = "123foo";
Character.isDigit(s.charAt(0));
System.out.println(Character.isDigit(mystring.charAt(0));
编辑:我搜索了Java文档,查看了字符串类上的方法,可以获取第一个字符,并查看了Character类上的方法,以查看是否有检查此类事物的方法。
我认为,在提问之前,您可以做同样的事情。
EDI2:我的意思是,尝试做事情,阅读/查找,如果找不到任何东西-请问。
我在第一次发布时犯了一个错误。isDigit是Character类上的静态方法。
使用正则表达式,例如^\d