开发者

Reversing string and toggle lower-upper-case

I need to write an application which takes a String as input. After processing, it should print out the string reversed, and all characters switched from lower to uppercase and vise versa. I want to achieve this using a StringBuilde开发者_开发技巧r.

Sample run:

Input: Hello Human

Output: NAMUh OLLEh


Here is a straight forward and simple way of solving the problem:

  1. Read user input using for instance the Scanner class. and the nextLine() method. (Construct the Scanner by giving it System.in as argument.)

  2. Create a StringBuilder.

  3. Fetch the array of characters from the input string, using for instance input.toCharArray()

  4. Reverse the array with Arrays.asList and Collections.reverse

    Collections.reverse(Arrays.asList(yourCharArray));
    
  5. Loop through the list using for instance a for-each loop.

    for (Character c : yourCharArray) {
        ...
    }
    
  6. For each character, check if c.isUpperCase (if so append c.toLowerCase()) else append c.toUpperCase().

(An alternative approach would be to give the StringBuilder the input-string as argument, and manipulate the string in-place using the reverse, charAt and setCharAt methods.)


To reverse a String use String reverse = new StringBuffer(YourString).reverse().toString();


Take a look at StringBuilder.reverse and Character.toLowerCase/Character.toUpperCase


Here's an "elite" 3-line solution:

    StringBuffer buffy = new StringBuffer("!GNIzA Ma").reverse();
    for (int i = 0; i < buffy.length(); i++)
        buffy.setCharAt(i, Character.isLetter(buffy.charAt(i)) ? (char) (buffy.charAt(i) ^ 32) : buffy.charAt(i));

    System.out.println(buffy); // "Am aZing!"

This works because the xor ^ with 32 (or 0x20) toggles the 3rd bit of the byte which changes upper to lower and visa versa. This toggling only works for letters of course.


      `function toggleCase(text){
         let toggledString='';
         for(let i=0;i<text.length;i++){
            if(text[i]==text[i].toUpperCase())
               toggledString+=text[i].toLowerCase();
            else if(text[i]==text[i].toLowerCase())
                    toggledString+=text[i].toUpperCase();
           }
         return toggledString;
       }`
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜