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 1
From Hans Dampf’s comment below:
Use java.lang.Character#isUpperCase() and #isLetter() instead of the magic numbers.
System.out.println("You're awesome");
what about org.apache.commons.lang3.StringUtils.isAllUpperCase() ?
return StringUtils.isAllUpperCase(String str);
lower case letter value is from 97 to 122. not upper case
Yeah, I’ve noticed that too. But the code itself is fine, an author made an inversion of lowercase letters, so now method works fine even if there are whitespaces, punctuation or Greek alphabet 🙂
Hi, there is an error in your writeup it should be Lower case letter value is from 97 to 122
s.toUpperCase().equals(s);
String a = “eLif”;
String b = a.toLowerCase();
if(a.equals(b))
System.out.println(“there is no uppercase letter in it”);
else
System.out.println(“there is a uppercase letter in it”);
How about using Regex? It might not outperform your solution but it is easier to understand and less verbose…
Pattern p = Pattern.compile(“[A-Z]*”);
System.out.println(p.matcher(“ABCD”).matches()); // true
System.out.println(p.matcher(“ABcD”).matches()); // false
System.out.println(p.matcher(“ABC123-#!.”).matches()); // false
What about using Character.getType(ch) == Character.UPPERCASE_LETTER ?
That’s just bad. What about languages using non-ASCII characters like german, french, and all the others?
I’d prefer to use java.lang.Character#isUpperCase() and #isLetter() instead of the magic numbers.
Your example will return false if the String contains any lower case characters. It won’t return false if there are any non-alpha chars like punctuations or numbers.
for example
testAllUpperCase(“ABC123-#!”) will return true. None of the chars are lower case.
If your objective is to test a string to ensure it contains ONLY upper case chars then:
Upper case characters are actually between 65 (‘A’) and 90 (‘Z’)
I would modify the ‘if’ statement to read
if ( c 90) return false;
OR
if(c ‘Z’) return false;
Both are functionally equivalent, but I prefer the latter as it is easier to read.
I always view the >= and <= operators as two step operators.
so for (c<= 'Z') you get
1) is c less than ( ‘Z’ as this would be outside the range.
Thanks. But I think the performance of your method is worse. The equals() method does the following:
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n– != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
from a string s1 create a copy s2, move to upper case s2 with toUpperCase method, so compare with s1.equals(s2)