简体   繁体   中英

Reverse a string word by word except the last letter of each word

I'd like to reverse a string word by word except the last letter of each word.

For example: "Hello how are you" -> lleHo ohw rae oyu

but I am getting output as: olleH woh era uoy

I'm not able to fix the last letter of each word.

This is my Java code for the above output:

public class Main

    {
    public static void main(String[] args) {
     String s = "Hello how are you  ";
      char [] ch = s.toCharArray();
      System.out.println(ch.length);
      int pos=0;
        for(int i=0;i<ch.length;i++)
        {
        
            if(ch[i]==' ')
            {
                   
                for(int j=i;j>=pos;j--)
                {
                    System.out.print(ch[j]);
                }
                pos=i+1;
                }
            }
    
    }
} 

Below is the solution to solve the problem:

public class Main { 
    
    public static void main(String[] args) { 
        //call the reverseSentence Method
        reverseSentence("Hello how are you");
    } 
    
    public static void reverseSentence(String sentence) {
        

        //Replacing multiple space with a single space
        sentence = sentence.replaceAll("[ ]{2,}", " ");

        //Split the array and store in an array
        String [] arr = sentence.split(" ");
        
        StringBuilder finalString = new StringBuilder();
        
        //Iterate through the array using forEach loop
        for(String str : arr) {
            
            //Creating substring of the word, leaving the last letter
            String s = str.substring(0, str.length() - 1);
            
            //Creating StringBuilder object and reversing the String
            StringBuilder sb = new StringBuilder(s);
            //Reversing the string and adding the last letter of the work again.
            s = sb.reverse().toString() + str.charAt(str.length() - 1);
            
            //Merging it with the final result
            finalString.append(s).append(" ");
        }
        
        //Printing the final result
        System.out.println(finalString.toString().trim());
    }
} 

What I have done is, firstly split all the words on spaces and store it inside an array. Now iterate through the array and get the substring from each word leaving the last letter of each word. And then I am using StringBuilder to reverse the String. Once that is done I am adding the last letter of the word to the reversed string and merging it with the finalString which is created.

I'd use regex replaceAll with a lambda to handle the reversal. \\S+ matches any sequence of non-space characters. This has the advantage of elegantly handling arbitrary whitespace. You could use \\w+ if you want to avoid reversing punctuation characters, although matching words like "isn't" and so forth suggests the problem devolves into natural language processing. I assume your specification is not so complex, though.

import java.util.regex.Pattern;

class Main {
    public static void main(String[] args) {
        String res = Pattern
            .compile("\\S+")
            .matcher("Hello how are you")
            .replaceAll(m -> {
                String s = m.group();
                return new StringBuilder(s.substring(0, s.length() - 1))
                    .reverse().toString() + s.charAt(s.length() - 1);
             });
        System.out.println(res); // => lleHo ohw rae oyu
    }
}

A simpler solution would be to just use the Java Stack data structure for each word (after a string.split) and just add each letter (except token.length-1).

public static void main(String[] args) {
    String string = "Hello how are you  ";
    final String[] tokens = string.split(" ");
    for (String token : tokens) {
        final Stack<Character> stack = new Stack<Character>();
        for (int i = 0; i < token.length()-1; i++) {
            stack.push(token.charAt(i));
        }
        while (!stack.empty()) {
            System.out.print(stack.pop());
        }
        System.out.print(token.charAt(token.length()-1) + " ");
    }
}

How do you think of this solution?

public class Main
{
    public static void main(String[] args) {
        String s = "Hello how are you  ";
        char [] ch = s.toCharArray();
        System.out.println(ch.length);
        int pos=0;
        for(int i=0;i<ch.length;i++)
        {
        
            if(ch[i]==' ')
            {
                System.out.print(ch[i]);
                for(int j=i-2;j>=pos;j--)
                {
                    System.out.print(ch[j]);
                }
                System.out.print(ch[i-1]);
                pos=i+1;
            }
        }
    
    }
} 
public class Main {
    public static void main(String[] args) {
        String s = "Hello how are you  ";
        final List<String> list = Arrays.asList(s.split(" "));
        StringBuilder builder = new StringBuilder();
        list.forEach(item ->{
            StringBuilder itemBuilder = new StringBuilder(item);
            final String rStr = itemBuilder.reverse().toString();
            builder.append(rStr.substring(1,rStr.length())).append(rStr.substring(0,1)).append(" ");
        });
        System.out.println(builder.toString());
    }
}

FP style:

String str = "Hello how are you";

String res = Arrays.stream(str.split(" "))
  .map(s ->
    new StringBuilder(s.substring(0, s.length() - 1)).reverse().toString() + s.substring(s.length() - 1)
  )
  .reduce((s, s1) -> s + " " + s1)
  .orElse("");

System.out.println(res); // lleHo ohw rae oyu

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM