Home > Software engineering >  Trying To convert String to lower/upper case respectively
Trying To convert String to lower/upper case respectively

Time:01-12

I'm trying to convert string to lowercase if it is uppercase and vice-versa. The code doesn't work as expected. Any idea what I'm doing wrong?

public class LowerNadUpperCase {

    public static void main(String[] args) {
        String output = "Elmar DidOkLTWdeee";
        System.out.println(toAlternativeString(output));
    }

    public static String toAlternativeString(String string) {
        String output = "";
        for(int i = 0; i < string.length(); i  ) {
            char c = string.charAt(i);
            if(Character.isLetter(c)){
                if(Character.isLowerCase(c)){
                    output  = Character.toUpperCase(c);
                    if(Character.isUpperCase(c)){
                        output  = Character.toLowerCase(c);
                    }  else{
                        output  = c;
                    }
                }
            }
        }
        return output;
    }
}

CodePudding user response:

Convert using predefine method try this

static void convertOpposite(StringBuffer str)
    {
        int ln = str.length();
 
        // Conversion using predefined methods
        for (int i = 0; i < ln; i  ) {
            Character c = str.charAt(i);
            if (Character.isLowerCase(c))
                str.replace(i, i   1,
                            Character.toUpperCase(c)   "");
            else
                str.replace(i, i   1,
                            Character.toLowerCase(c)   "");
        }
    }

public static void main(String[] args)
    {
        StringBuffer str = new StringBuffer("asasDAaQWADa");
        convertOpposite(str);
 
        System.out.println(str);
    }

Dont take extra variable it will convert by replace character.

CodePudding user response:

So, your basic problem is in your logic (I know, obvious right)

if (Character.isLetter(c)) {
    if (Character.isLowerCase(c)) {
        output  = Character.toUpperCase(c);
        if (Character.isUpperCase(c)) {
            output  = Character.toLowerCase(c);
        } else {
            output  = c;
        }
    }
}
  • if c is not a letter ... do nothing
  • Related