How do I move char characters to left or to right in a string?
3 Answers
Reading the input string backwards you need to keep every character on an odd index of each word and any blank characters.
You could start with this snippet. See it as a PoC to demonstrate the logic. Optimisations are possible.
String encoded = "bxoqb swi eymrawn yim";
StringBuilder decoded = new StringBuilder();
boolean keep = true;
for (int i = encoded.length() - 1; i >= 0; i--) {
if (encoded.charAt(i) != ' ') {
if (keep) {
decoded.append(encoded.charAt(i));
}
keep = !keep;
} else {
decoded.append(' ');
keep = true;
}
}
System.out.println("decoded = " + decoded);
output
decoded = my name is bob
explanation
- the
for-loopprocesses the string backwards, so the characters are processed asmiy nwarmye iws bqoxb - the variable
ihold the current index position in the stringencoded - as we want to keep only the characters on odd positions in a word the variable
keepis used as a indicator - when the variable
keepistruewe append the current character (the one on positioniin stringencoded) to the string bufferdecoded - if the current processed character is not a
the value ofkeepis negated (true->false, false->true), so we append characters on every odd position - as we need to keep
between the words also we have to treat this separately, eachis appended todecodedandkeepis set totrueso the next non-blank character would be added too
1 Comment
Kayaman
Your profile says "keen to share knowledge with others ("the best way to learn is to teach" - Frank Oppenheimer)". However you're not teaching, you're giving answers. It would be more useful (for the obvious student/homework questions) to give out advice so they can reach the solution themselves.
You have to use StringBuffer to reverse the sentence.Then you can split your sentence word by word using the spaces between the words. After that basic java knowledge ...
String ss = "bxoqb swi eymrawn yim";
StringBuilder buffer = new StringBuilder(ss);
String word[] = buffer.reverse().toString().split(" ");
for (String word1 : word) {
char c[]=word1.toCharArray();
for(int x=0;x<c.length;x++){
if(x%2==0){
System.out.print(c[x]);
}
}
System.out.print(" ");
}
split(" ");as demonstrated in Viswanath's answer below. Then you can process each word separately with theforloop you have now. You'll need another (outer)forloop to process all the words.