2

I have my code to switch the case from upper to lower and vice versa. I also have it to where it will toggle upper to lower, and lower to upper. My question is; is there a way I can get it to also include the character such as a comma or a period. For example, if I type in the string "Hello, there." I will get: "HELLO, THERE.", "hello, there" and "hELLOTHERE". How can I get it to where my third output will say "hELLO, THERE."

import java.util.*;
public class UpperLower2
{

    public static void main(String[] args)
    {
        System.out.println("Enter in a sentence:"); 
        Scanner input = new Scanner(System.in); 
        String sentence = input.nextLine();


        System.out.println("All uppercase:" + sentence.toUpperCase());
        System.out.println("All lowercase:" + sentence.toLowerCase()); 
        System.out.println("Converted String:" + toggleString(sentence)); 
        input.close(); 
     }

    public static String toggleString(String sentence)
    {
       String toggled = ""; 
       for(int i=0; i<sentence.length(); i++)
       {


           char letter = sentence.charAt(i); 

           if(Character.isUpperCase(sentence.charAt(i)))
           {
                letter = Character.toLowerCase(letter); 
                toggled = toggled + letter; 

           }
           else if(Character.isLowerCase(sentence.charAt(i)))
           {
               letter = Character.toUpperCase(letter);
               toggled = toggled + letter; 
           }

       }
       return toggled; 

   }

}

Mureinik
  • 297,002
  • 52
  • 306
  • 350
ecain
  • 1,282
  • 5
  • 23
  • 54
  • [General Kenobi!](https://www.reddit.com/r/PrequelMemes/comments/9mbgi0/was_doing_my_apcs_hw_when_i_found_this_gem/) – RaviRavioli Oct 08 '18 at 03:35

8 Answers8

8

If a character is neither upper case nor lowercase, you should just take it as is. Also, don't use a String to accumulate your output - this is what StringBuilders are for:

public static String toggleString(String sentence) {
    StringBuilder toggled = new StringBuilder(sentence.length());
    for (char letter : sentence.toCharArray()) {
        if(Character.isUpperCase(letter)) {
            letter = Character.toLowerCase(letter);
        } else if(Character.isLowerCase(letter)) {
            letter = Character.toUpperCase(letter);
        }

        toggled.append(letter);

    }
    return toggled.toString();
}

EDIT:
A similar implementation in Java 8 semantics, without having to loop over the string yourself:

public static String toggleStringJava8(String sentence) {
    return sentence.chars().mapToObj(c -> {
        if (Character.isUpperCase(c)) {
            c = Character.toLowerCase(c);
        } else if (Character.isLowerCase(c)) {
            c = Character.toUpperCase(c);
        }
        return String.valueOf((char)c);
    }).collect(Collectors.joining());
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

Use the Apache commons lang API StringUtils class. UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize - changes the case of a String

To toggle the cases, Use the

swapCase(String str)

Swaps the case of a String changing upper and title case to lower case, and lower case to upper case.

Also you do not need to write any code to handle ' or . or any other these kind of characters.String Util will do it all..

Example:

        String inputString = "Hello, there";
        
        System.out.println(StringUtils.swapCase(inputString));
        System.out.println(StringUtils.upperCase(inputString));
        System.out.println(StringUtils.lowerCase(inputString));

Output:
hELLO, THERE
HELLO, THERE
hello, there

Community
  • 1
  • 1
027
  • 1,553
  • 13
  • 23
  • @SandeepRoy it does work. You probably haven't yet learned to use third-party libraries. – slim Jul 12 '17 at 10:27
  • [General Kenobi!](https://www.reddit.com/r/PrequelMemes/comments/9mbgi0/was_doing_my_apcs_hw_when_i_found_this_gem/) – RaviRavioli Oct 08 '18 at 03:35
1

Given the source code that you posted, you now have an if-statement with two branches: one for the case where the character was upper-case and one when the character was lower-case. Characters like comma and other punctuation symbols don't have upper or lower-case, so they are ignored by your if-statement and else-block.

To work around that, add another else block to the statement:

else {
    toggled = toggled + letter; 
}

After you have that working, you should look into making your code cleaner.

You now have the statement toggled = toggled + letter; three times in your code; you can change that into one time:

       char letter = sentence.charAt(i); 

       if(Character.isUpperCase(sentence.charAt(i)))
       {
            letter = Character.toLowerCase(letter); 
       }
       else if(Character.isLowerCase(sentence.charAt(i)))
       {
           letter = Character.toUpperCase(letter);
       }
       // else {
       // }
       // You can remove the latest `else` branch now, because it is empty.

       toggled = toggled + letter; 

Also, the preferred way to build strings in Java is using StringBuilder instead of the + operator on strings. If you search on StackOverflow for StringBuilder you'll get plenty of examples on how to use that.

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
1

Using bit manipulation:

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scan= new Scanner(System.in);
        String s= scan.next();
        for(int i=0;i<s.length();i++){
            System.out.print((char)(s.charAt(i)^32));
        }
    }
}
dbc
  • 104,963
  • 20
  • 228
  • 340
0

We can simply convert the incoming String into char[] and then toggle them individually. Worked for me!!!

import java.util.Scanner;
@SuppressWarnings("unused")
public class One {
public static void main(String[] args) {
System.out.println("Enter a Word with toggled alphabets");  
Scanner sc=new Scanner(System.in);

String line =sc.nextLine();
char[] arr= line.toCharArray();

for(char ch: arr)
  {
if(Character.isUpperCase(ch)){
ch= Character.toLowerCase(ch);
}
else if(Character.isLowerCase(ch)){
    ch= Character.toUpperCase(ch);
}
System.out.print(ch);
}}} 
Ronit Oommen
  • 3,040
  • 4
  • 17
  • 25
0

You can do it with one line of code in Java 8:

String newText = text.chars() .mapToObj(ch -> Character.isLowerCase(ch) ? String.valueOf(Character.toUpperCase((char)ch)) : String.valueOf(Character.toLowerCase((char)ch))) .collect(Collectors.joining());

VHS
  • 9,534
  • 3
  • 19
  • 43
0

We can do this by comparing all the characters of the string with all the upper case and lowercase alphabets. If the character matches with uppercase alphabet, replace it with corresponding lowercase and vice versa.

import java.util.Scanner;
class TestClass {
    public static void main(String args[] ) throws Exception {
        Scanner scan = new Scanner(System.in);
        String S = scan.next();
        char []a ={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
        char []b ={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
        char [] ch = S.toCharArray();
        for(int i=0;i<ch.length;i++){
           for(int j=0;j<a.length;j++){
               if(ch[i]==a[j]){
                   ch[i]=b[j];
               }
               else if(ch[i]==b[j]){
                   ch[i]=a[j];
               }
           }
        }
        String text = new String(ch);
        System.out.println(text);
    }
}
0

The logic behind that is you should know ASCII value. A-Z is 65-90 and a-z is 97-122. The relative difference between Capital and small letters is '32'.

Please see the following logic.

static void Toggle_String(char[] str)
{
    for(int i=0;i<str.length;i++)
    {
        if(str[i]>='a' && str[i]<='z')
        {
            str[i]=(char)(str[i]-32);
        }
        else if(str[i]>='A' &&str[i]<='Z')
        {
            str[i]=(char)(str[i]+32);
        }
        else
        {
            i++;
        }
    }
    for(int i=0;i<str.length;i++)
    {
    System.out.print(str[i]);
    }
}

OutPut: ImNilesH iMnILESh