forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpper.java
More file actions
57 lines (49 loc) · 1.52 KB
/
Upper.java
File metadata and controls
57 lines (49 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.thealgorithms.strings;
public final class Upper {
private Upper() {
}
/**
* Driver Code
*/
public static void main(String[] args) {
String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"};
for (String s : strings) {
assert toUpperCase(s).equals(s.toUpperCase());
}
}
/**
* Converts all the characters in this {@code String} to upper case.
*
* @param s the string to convert
* @return the {@code String}, converted to uppercase.
* @throws IllegalArgumentException if {@code s} is null
*/
public static String toUpperCase(String s) {
if (s == null) {
throw new IllegalArgumentException("Input string cannot be null");
}
if (s.isEmpty()) {
return s;
}
// Check if any lowercase letter exists before creating a new String
boolean hasLower = false;
for (int i = 0; i < s.length(); i++) {
if (Character.isLowerCase(s.charAt(i))) {
hasLower = true;
break;
}
}
// If no lowercase characters, return the same string
if (!hasLower) {
return s;
}
// Convert lowercase letters to uppercase
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (Character.isLowerCase(chars[i])) {
chars[i] = Character.toUpperCase(chars[i]);
}
}
return new String(chars);
}
}