在Java中,在不使用正则表达式的情况下查找字符串中的第一个字符是否为大写。
发布于 2010-12-16 01:28:22
假设s
不为空:
Character.isUpperCase(s.charAt(0))
或者,正如divec所提到的,使其适用于码位高于U+FFFF
的字符。
Character.isUpperCase(s.codePointAt(0));
发布于 2010-12-16 01:28:47
有很多方法可以做到这一点,但最简单的方法似乎是以下一种:
boolean isUpperCase = Character.isUpperCase("My String".charAt(0));
发布于 2015-09-06 23:38:38
不要忘记检查字符串是否为空或null
。如果我们忘记检查null
或empty,那么如果给定的字符串为null或empty,我们将得到NullPointerException
或StringIndexOutOfBoundException
。
public class StartWithUpperCase{
public static void main(String[] args){
String str1 = ""; //StringIndexOfBoundException if
//empty checking not handled
String str2 = null; //NullPointerException if
//null checking is not handled.
String str3 = "Starts with upper case";
String str4 = "starts with lower case";
System.out.println(startWithUpperCase(str1)); //false
System.out.println(startWithUpperCase(str2)); //false
System.out.println(startWithUpperCase(str3)); //true
System.out.println(startWithUpperCase(str4)); //false
}
public static boolean startWithUpperCase(String givenString){
if(null == givenString || givenString.isEmpty() ) return false;
else return (Character.isUpperCase( givenString.codePointAt(0) ) );
}
}
https://stackoverflow.com/questions/4452939
复制相似问题