aheroafaked
aheroafaked

Reputation: 31

java string iterations of char variables

How do I move char characters to left or to right in a string?

Upvotes: 2

Views: 92

Answers (3)

SubOptimal
SubOptimal

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

  • the for-loop processes the string backwards, so the characters are processed as miy nwarmye iws bqoxb
  • the variable i hold the current index position in the string encoded
  • as we want to keep only the characters on odd positions in a word the variable keep is used as a indicator
  • when the variable keep is true we append the current character (the one on position i in string encoded) to the string buffer decoded
  • if the current processed character is not a the value of keepis 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, each is appended to decoded and keep is set to true so the next non-blank character would be added too

Upvotes: 2

Madushan Perera
Madushan Perera

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

Viswanath Donthi
Viswanath Donthi

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

Related Questions