How to detect if string contains only uppercase letter in Java

共 360字,需浏览 1分钟

 ·

2020-07-20 10:19

来源:https://www.programcreek.com/2011/04/a-method-to-detect-if-string-contains-1-uppercase-letter-in-java/

My approach

This method loop through each character in the string, and determine if each character is in upper case. Upper case letter value is from 97 to 122.

public static boolean testAllUpperCase(String str){
for(int i=0; i<str.length(); i++){
char c = str.charAt(i);
if(c >= 97 && c <= 122) {
return false;
}
}
//str.charAt(index)
return true;
}

Any other better approach regarding the performance?

Option

From Hans Dampf's comment below:

Use java.lang.Character#isUpperCase() and #isLetter() instead of the magic numbers.


浏览 31
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐