[java] how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

Alternately display any text that is typed in the textbox

//     in either Capital or lowercase depending on the original
//     letter changed.  For example:  CoMpUtEr will convert to
//     cOmPuTeR and vice versa.
    Switch.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e )

            String characters = (SecondTextField.getText()); //String to read the user input
            int length = characters.length();  //change the string characters to length

         for(int i = 0; i < length; i++)  //to check the characters of string..
         {             
            char character = characters.charAt(i);          

            if(Character.isUpperCase(character)) 
            {
                SecondTextField.setText("" + characters.toLowerCase());

            }
            else  if(Character.isLowerCase(character))
            {
                 SecondTextField.setText("" + characters.toUpperCase()); //problem is here, how can i track the character which i already change above, means lowerCase**
                }               
         }}     
    });

This question is related to java string uppercase lowercase

The answer is


public class Toggle {
public static String toggle(String s) {
    char[] ch = s.toCharArray();

    for (int i = 0; i < s.length(); i++) {
        char charat = ch[i];
        if (Character.isUpperCase(charat)) {
            charat = Character.toLowerCase(charat);
        } else
            charat = Character.toUpperCase(charat);
        System.out.print(charat);
    }
    return s;
  }

public static void main(String[] args) {
    toggle("DivYa");
   }
  }

This is a better approach without using any String function.

public static String ReverseCases(String str) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
      char temp;
      if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
        temp = (char)(str.charAt(i) - 32);
      }
      else if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z'){
        temp = (char)(str.charAt(i) + 32);
      }
      else {
        temp = str.charAt(i);
      }

      sb.append(temp);
    }
    return sb.toString();
  }

Methods description:

*toLowerCase()* Returns a new string with all characters converted to lowercase.

*toUpperCase()* Returns a new string with all characters converted to uppercase.

For example:

"Welcome".toLowerCase() returns a new string, welcome

"Welcome".toUpperCase() returns a new string, WELCOME


StringBuilder b = new StringBuilder();

Scanner s = new Scanner(System.in);
String n = s.nextLine();

for(int i = 0; i < n.length(); i++) {
    char c = n.charAt(i);

    if(Character.isLowerCase(c) == true) {
        b.append(String.valueOf(c).toUpperCase());
    }
    else {
        b.append(String.valueOf(c).toLowerCase());
    }
}

System.out.println(b);

String name = "Vikash";
String upperCase = name.toUpperCase();
String lowerCase = name.toLowerCase();

You don't have to track whether you've already changed the character from upper to lower. Your code is already doing that since it's basically:

1   for each character x:
2       if x is uppercase:
3           convert x to lowercase
4       else:
5           if x is lowercase:
6                convert x to uppercase.

The fact that you have that else in there (on line 4) means that a character that was initially uppercase will never be checked in the second if statement (on line 5).

Example, start with A. Because that's uppercase, it will be converted to lowercase on line 3 and then you'll go back up to line 1 for the next character.

If you start with z, the if on line 2 will send you directly to line 5 where it will be converted to uppercase. Anything that's neither upper nor lowercase will fail both if statements and therefore remain untouched.


public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String satr=scanner.nextLine();
    String newString = "";
    for (int i = 0; i < satr.length(); i++) {
        if (Character.isUpperCase(satr.charAt(i))) {
            newString+=Character.toLowerCase(satr.charAt(i));
        }else newString += Character.toUpperCase(satr.charAt(i));
    }
    System.out.println(newString);
}

The problem is that you are trying to set the value of SecondTextField after checking every single character in the original string. You should do the conversion "on the side", one character at a time, and only then set the result into the SecondTextField.

As you go through the original string, start composing the output from an empty string. Keep appending the character in the opposite case until you run out of characters. Once the output is ready, set it into SecondTextField.

You can make an output a String, set it to an empty string "", and append characters to it as you go. This will work, but that is an inefficient approach. A better approach would be using a StringBuilder class, which lets you change the string without throwing away the whole thing.


//This is to convert a letter from upper case to lower case
import java.util.Scanner;
    public class ChangeCase {
        public static void main(String[]args) {

            String input;
            Scanner sc= new Scanner(System.in);
                System.out.println("Enter Letter from upper case");
                input=sc.next();

            String result;
            result= input.toLowerCase();
            System.out.println(result);
        }
    }

import java.util.Scanner;
class TestClass {
    public static void main(String args[]) throws Exception {
        Scanner s = new Scanner(System.in);
        String str = s.nextLine();
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            if (Character.isUpperCase(ch[i])) {
                ch[i] = Character.toLowerCase(ch[i]);
            } else {
                ch[i] = Character.toUpperCase(ch[i]);
            }
        }
        System.out.println(ch);
    }
}

This is a better method :-

void main()throws IOException
{
    System.out.println("Enter sentence");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String str = br.readLine();
    String sentence = "";
    for(int i=0;i<str.length();i++)
    {
        if(Character.isUpperCase(str.charAt(i))==true)
        {
            char ch2= (char)(str.charAt(i)+32);
            sentence = sentence + ch2;
        }
        else if(Character.isLowerCase(str.charAt(i))==true)
        {
            char ch2= (char)(str.charAt(i)-32);
            sentence = sentence + ch2;
        }
        else
        sentence= sentence + str.charAt(i);

    }
    System.out.println(sentence);
}

    String str1,str2;
    Scanner S=new Scanner(System.in);
    str1=S.nextLine();
    System.out.println(str1);
    str2=S.nextLine();
    str1=str1.concat(str2);
    System.out.println(str1.toLowerCase()); 

Here you are some other version:

public class Palindrom {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a word to check: ");
    String checkWord = sc.nextLine();
    System.out.println(isPalindrome(checkWord));
    sc.close();

}

public static boolean isPalindrome(String str) {        
    StringBuilder secondSB = new StringBuilder();
    StringBuilder sb = new StringBuilder();
    sb.append(str);
    for(int i = 0; i<sb.length();i++){
        char c = sb.charAt(i);
        if(Character.isUpperCase(c)){
            sb.setCharAt(i, Character.toLowerCase(c));
        }
    }
    secondSB.append(sb);
    return sb.toString().equals(secondSB.reverse().toString());
}

}


If you look at characters a-z, you'll see that all of them have the 6th bit is set to 1. Where in A-Z 6th bit is not set.

A = 1000001    a = 1100001
B = 1000010    b = 1100010
C = 1000011    c = 1100011
D = 1000100    d = 1100100     
...
Z = 1011010    z = 1111010

So all we need to do is to iterate through each character from a given string and then do XOR(^) with 32. In this way, the 6th bit can swap.

Look at the below code for simply changing the string case without using any if-else conditions.

public final class ChangeStringCase {
    public static void main(String[] args) {
        String str = "Hello World";
        for (int i = 0; i < str.length(); i++) {
            char ans = (char)(str.charAt(i) ^ 32);
            System.out.print(ans); // Final Output: hELLO wORLD
        }
    }
}

Time Complexity: O(N) where N = Length of the string.

Space Complexity: O(1)


You can use StringUtils.swapCase() from org.apache.commons


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to uppercase

Capitalize the first letter of string in AngularJs Ignoring upper case and lower case in Java Convert from lowercase to uppercase all values in all character variables in dataframe In Android EditText, how to force writing uppercase? how to convert Lower case letters to upper case letters & and upper case letters to lower case letters How to convert a string from uppercase to lowercase in Bash? How to change a string into uppercase Java Program to test if a character is uppercase/lowercase/number/vowel How do I lowercase a string in Python? Capitalize or change case of an NSString in Objective-C

Examples related to lowercase

Ignoring upper case and lower case in Java how to convert Lower case letters to upper case letters & and upper case letters to lower case letters How to detect lowercase letters in Python? .toLowerCase not working, replacement function? How to convert a string from uppercase to lowercase in Bash? How to convert array values to lowercase in PHP? Java Program to test if a character is uppercase/lowercase/number/vowel How do I lowercase a string in Python? How do I lowercase a string in C? How to convert a string to lower case in Bash?