Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 26 additions & 8 deletions src/main/java/com/thealgorithms/strings/Upper.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.thealgorithms.strings;

public final class Upper {

private Upper() {
}

Expand All @@ -15,25 +16,42 @@ public static void main(String[] args) {
}

/**
* Converts all the characters in this {@code String} to upper case
* 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 connot be null");
throw new IllegalArgumentException("Input string cannot be null");
}
if (s.isEmpty()) {
return s;
}
StringBuilder result = new StringBuilder(s);
for (int i = 0; i < result.length(); ++i) {
char currentChar = result.charAt(i);
if (Character.isLetter(currentChar) && Character.isLowerCase(currentChar)) {
result.setCharAt(i, Character.toUpperCase(currentChar));

// 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;
}
}
return result.toString();

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