Home > Mobile >  Reverse odd length words from a string
Reverse odd length words from a string

Time:10-30

I am trying to reverse the words from a string = "One Two three Four" whose length is odd, I am using StringBuilder class to reverse the words my expected output is "enO owT eerht Four" but I am getting "eerht enO Two Four" here the order is not correct also it is not reversing "Two", what's wrong with my code also please provide a solution to it.

package QAIntvSprint;

import java.util.Arrays;

public class SecretAgent {
  static StringBuilder sb = new StringBuilder();

  public static void main(String[] args) {
    secretAgentII("One Two three Four");
  }

  static void secretAgentII(String s) {
    String[] arr = s.split(" ");
    System.out.println(Arrays.toString(arr));
    int i;
    for (i = 0; i < arr.length; i  ) {
      if (arr[i].length() % 2 == 0) {
        sb.append(arr[i]   " ");
      } else {
        sb.append(arr[i]).reverse().append(" ");
      }
    }
    System.out.println(sb.toString());
  }
}

output is below enter image description here

CodePudding user response:

I would use a stream approach here:

String input = "One Two three Four";
String output = Arrays.stream(input.split(" "))
                      .map(x -> new StringBuilder(x).reverse().toString())
                      .collect(Collectors.joining(" "));
System.out.println(output);  // enO owT eerht ruoF

CodePudding user response:

Your problem is that you are adding the strings to the same instance of StringBuilder and reversing it as a whole. The key is to create a temporary buffer to reverse the string and once it is reversed, append the contents of the temporary buffer to the sb buffer.

To fix, replace the contents of the else block with the following snippet:

StringBuilder temp = new StringBuilder(arr[i]).reverse();
sb.append(temp.toString()).append(" ");

The program now outputs

[One, Two, three, Four]
enO owT eerht Four 

CodePudding user response:

You can use Pattern like this.

static final Pattern WORD = Pattern.compile("\\S ");

static String secretAgentII(String s) {
    return WORD.matcher(s)
        .replaceAll(m -> m.group().length() % 2 == 0
            ? m.group()
            : new StringBuilder(m.group()).reverse().toString());
}

public static void main(String[] args) {
    System.out.println(secretAgentII("One     Two three Four"));
}

output:

enO     owT eerht Four
  • Related