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 OLLEhHere is a straight forward and simple way of solving the problem:
Read user input using for instance the
Scanner
class. and thenextLine()
method. (Construct theScanner
by giving itSystem.in
as argument.)Create a
StringBuilder
.Fetch the array of characters from the input string, using for instance
input.toCharArray()
Reverse the array with
Arrays.asList
andCollections.reverse
Collections.reverse(Arrays.asList(yourCharArray));
Loop through the list using for instance a for-each loop.
for (Character c : yourCharArray) { ... }
For each character, check if
c.isUpperCase
(if so appendc.toLowerCase()
) else appendc.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;
}`
精彩评论