Uppercase and lowercase letters (with.Java)
This article looks into the âuppercase and lowercase lettersâ problem.
As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.
Letâs look at the problem first.
problem
When the string my_string is given as a parameter, complete the solution function to return a string with uppercase letters converted to lowercase and lowercase letters converted to uppercase.
Restrictions
- 1 †length of my_string †1,000
- my_string consists only of uppercase and lowercase English letters.
Input/Output Example
my_string | result |
---|---|
âcccCCCâ | âCCCcccâ |
âabCdEfghIJâ | âABcDeFGHijâ |
My solution to the problem
class Solution {
public String solution(String my_string) {
StringBuilder answer = new StringBuilder();
char[] chArr = my_string.toCharArray();
for(char ch : chArr){
String str = Character.toString(ch);
if(ch >= 65 && 90 >= ch){
answer.append(str.toLowerCase());
}else{
answer.append(str.toUpperCase());
}
}
return answer.toString();
}
}
Solution explanation
This code is a method that converts all uppercase letters in a given string to lowercase and lowercase to uppercase.
To do this, we create a StringBuilder object and loop through it, converting the string to a char array.
For each character, the decision is made based on the ASCII code value, where 65 to 90 represent uppercase letters A to Z. Therefore, characters that fall within this range are converted to lowercase letters, and characters that do not (i.e. lowercase letters) are converted to uppercase letters.
The reason for using the char type like this is because it is suitable for determining the case of characters using ASCII codes.
Since the char type can be converted to a number, you can use ASCII code in this way.
On the other hand, the String type is a value for the entire string, so it is impossible to use ASCII code directly.
And methods such as toUpperCase and toLowerCase are methods of the String class, so they can only be used on String objects.
Since the char type does not have a method like this, it is used after converting the ch type to the String type for case conversion.
This conversion is done via Character.toString(ch).