Reputation: 31
How do I move char characters to left or to right in a string?
Upvotes: 2
Views: 92
Reputation: 22993
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
for-loop
processes the string backwards, so the characters are processed as miy nwarmye iws bqoxb
i
hold the current index position in the string encoded
keep
is used as a indicatorkeep
is true
we append the current character (the one on position i
in string encoded
) to the string buffer decoded
the value of keep
is negated (true->false, false->true), so we append characters on every odd position
between the words also we have to treat this separately, each
is appended to decoded
and keep
is set to true
so the next non-blank character would be added tooUpvotes: 2
Reputation: 2598
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(" ");
}
Upvotes: 0
Reputation: 1821
Try this:
StringBuilder builder = new StringBuilder();
String[] charArray = encoded.split(" ");
for(int i = charArray.length-1 ; i >= 0; i--){
builder.append(charArray[i]);
}
String decoded = builder.toString();
Upvotes: 0