Convert java char inside string to lowerCase / upperCase
I have a string called "originalstring" that contains a sentence with mixed upper and lower case characters.
I just want to flip the string so that if the character is lowercase it is uppercase and vice versa, and return it.
I tried this code which returns the original string in upperCase:
for (int i = 0; i < originalString.length(); i++) {
char c = originalString.charAt(i);
if (Character.isUpperCase(c)) {
originalString += Character.toLowerCase(c);
}
if (Character.isLowerCase(c)) {
originalString += Character.toUpperCase(c);
}
}
return originalString;
source to share
You are adding characters to the original string. Also, it means that your loop for
will never reach the end of the loop iteration for
because it originalString.length()
also changes every loop. It's an endless loop.
Instead, create StringBuilder
one that stores the converted characters as you iterate over the original string. Convert it to String
and return it to the end.
StringBuilder buf = new StringBuilder(originalString.length());
for (int i = 0; i < originalString.length(); i++) {
char c = originalString.charAt(i);
if (Character.isUpperCase(c)) {
buf.append(Character.toLowerCase(c));
}
else if (Character.isLowerCase(c)) {
buf.append(Character.toUpperCase(c));
}
// Account for case: neither upper nor lower
else {
buf.append(c);
}
}
return buf.toString();
source to share
Common-lang provides a function swapCase
, see the doc . Sample from doc:
StringUtils.swapCase(null) = null
StringUtils.swapCase("") = ""
StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
And if you really want to do it yourself, you can check the common-lang sourceStringUtils
Instead of using existing utilities, you can try converting using a boolean operation:
To uppercase:
char upperChar = (char) (c & 0x5f)
Lowercase:
char lowerChar = (char) (c ^ 0x20)
In your program:
StringBuilder result = new StringBuilder(originalString.length());
for (int i = 0; i < originalString.length(); i++) {
char c = originalString.charAt(i);
if (Character.isUpperCase(c)) {
result.append((char) (c ^ 0x20));
}
else if ((c >= 'a') && (c <= 'z')) {
result.append((char) (c & 0x5f));
}
else {
result.append(c);
}
}
System.out.println(result);
source to share