In Java, how to find if first character in a strin

2019-01-11 00:15发布

In Java, find if the first character in a string is upper case without using regular expressions.

8条回答
地球回转人心会变
2楼-- · 2019-01-11 00:38

Don't forget to check whether the string is empty or null. If we forget checking null or empty then we would get NullPointerException or StringIndexOutOfBoundException if a given String is null or empty.

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) ) );
        }

    }
查看更多
在下西门庆
3楼-- · 2019-01-11 00:41

Assuming s is non-empty:

Character.isUpperCase(s.charAt(0))

or, as mentioned by divec, to make it work for characters with code points above U+FFFF:

Character.isUpperCase(s.codePointAt(0));
查看更多
再贱就再见
4楼-- · 2019-01-11 00:44

There is many ways to do that, but the simplest seems to be the following one:

boolean isUpperCase = Character.isUpperCase("My String".charAt(0));
查看更多
走好不送
5楼-- · 2019-01-11 00:46

we can find upper case letter by using regular expression as well

private static void findUppercaseFirstLetterInString(String content) {
    Matcher m = Pattern
            .compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(
                    content);
    System.out.println("Given input string : " + content);
    while (m.find()) {
        if (m.group(1).equals(m.group(1).toUpperCase())) {
            System.out.println("First Letter Upper case match found :"
                    + m.group());
        }
    }
}

for detailed example . please visit http://www.onlinecodegeek.com/2015/09/how-to-determines-if-string-starts-with.html

查看更多
Emotional °昔
6楼-- · 2019-01-11 00:46
String yourString = "yadayada";
if (Character.isUpperCase(yourString.charAt(0))) {
    // print something
} else {
    // print something else
}
查看更多
【Aperson】
7楼-- · 2019-01-11 00:50

If you have to check it out manually you can do int a = s.charAt(0)

If the value of a is between 65 to 90 it is upper case.

查看更多
登录 后发表回答