简体   繁体   中英

Better way to invert cases of characters in a string in Java

As a novice Java programmer who barely got started in Java programming, I am totally exhausted in trying to find a solution to this issue. A course that I am currently studying gave homework that asked me to create a Java class that has a sort of “reverse” method that returns a new version of the string of the current string where the capitalization is reversed (ie, lowercase to uppercase and uppercase to lowercase) for the alphabetical characters specified in a given condition. Say if I were to reverse “abc, XYZ; 123.” using reverse("bcdxyz@3210."), it must return "aBC, xyz; 123.". (PS: the class ignores numbers and special characters and the variable "myString" is where the "abc, XYZ; 123." goes to.). So far, I've only managed to return out "aBC, XYZ; 123." with the code below. Am I missing something here?

public String reverse(String arg) {
    // TODO Implement method 
    String arg_no_sym = arg.replaceAll("[^a-zA-Z0-9]","");
    String arg_perfect = arg_no_sym.replaceAll("\\d","");
    
    if (myString != null) {
        char[] arrayOfReplaceChars = arg_perfect.toCharArray();
        char[] arrayOfmyString = myString.toCharArray();
        for (int i = 0; i < arg_perfect.length(); i++) {
            myString = myString.replace(String.valueOf((arrayOfReplaceChars[i])), String.valueOf((arrayOfReplaceChars[i])).toUpperCase()); 
        }
        return myString;
    }
    else {
        return "";
    }
}

How about using the methods isUpperCase() and isLowerCase() to check the case of the letters and then use toUpperCase() and toLowerCase() to change the case of them?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM