ANSHUMAN MISHRA
ANSHUMAN MISHRA

Reputation: 57

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;
                }
            }
    
    }
} 

Upvotes: 1

Views: 1501

Answers (7)

Ashu
Ashu

Reputation: 49

I think this one is also good.

String[] s = "Hello how are you".split(" ");
    String revSentence = "";
    for (int i=0; i<s.length;i++){
        String c = s[i];
        String revWord = "";
        {
            for (int j=c.length()-2;j>=0; j--)
            {
                revWord = revWord+c.charAt(j);
            }
            revWord =revWord+c.charAt(c.length()-1);
            revSentence =revSentence+revWord+" ";

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

Upvotes: 0

java-addict301
java-addict301

Reputation: 4136

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) + " ");
    }
}

Upvotes: 0

Prateek Srivastava
Prateek Srivastava

Reputation: 223

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.

Upvotes: 1

Dmytro Mitin
Dmytro Mitin

Reputation: 51703

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

Upvotes: 0

Ajeet Maurya
Ajeet Maurya

Reputation: 660

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());
    }
}

Upvotes: 0

ggorlen
ggorlen

Reputation: 57344

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
    }
}

Upvotes: 1

user14325562
user14325562

Reputation:

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;
            }
        }
    
    }
} 

Upvotes: 0

Related Questions