Home > Enterprise >  Reverse print only words in a given string ,number should not be reversed, i need alternate methods
Reverse print only words in a given string ,number should not be reversed, i need alternate methods

Time:05-01

Reverse print only words in a given string ,number should not be reversed

Given String : Testing 23 a 42 testing

Expected output : gnitseT 23 a 42 gnitset

i have used this Method

        public class ReverseString{
        public static void main(String[]args){

        String str= "Testing 23 a 42 testing";
        String[] split = str.split(" ");
        for (int i = 0; i < split.length; i  ) {
            try {
                Integer val = Integer.valueOf(split[i]);
                System.out.print(val);  
            } catch (Exception e) {
                for(int j=split[i].length()-1;j>=0;j--) {
                    System.out.print(split[i].charAt(j));
                }
            }
        if(split.length-1>i)System.out.print(" ");
        }
    }
}

Output : gnitseT 23 a 42 gnitset

CodePudding user response:

Tokenize the input. I would prefer \\s to start by splitting on consecutive whitespace. If it isn't the first token, emit a space. Use a regular expression to determine if the token is all digits (\\d ), if so emit it. Otherwise, emit the reverse token. After iterating all of the tokens print a newline. Like,

public static void main(String[] args) {
    String str = "Testing 23 a 42 testing";
    String[] split = str.split("\\s ");
    for (int i = 0; i < split.length; i  ) {
        if (i != 0) {
            System.out.print(" ");
        }
        if (split[i].matches("\\d ")) {
            System.out.print(split[i]);
        } else {
            System.out.print(new StringBuilder(split[i]).reverse());
        }
    }
    System.out.println();
}

Outputs (as requested)

gnitseT 23 a 42 gnitset

CodePudding user response:

Use Java streams:

    String str = "Testing 23 a 42 testing";

    System.out.println(Arrays.stream(str.split(" ")) //
        .map(s -> s.matches("\\d ") ? s : new StringBuffer(s).reverse().toString()) //
        .collect(Collectors.joining(" ")));
  • Related