user4274413
user4274413

Reputation:

Reverse every 2nd word of a sentence

I am trying to reverse every 2nd words of every single sentence like

If a given string is :

My name is xyz

The desired output should be :

My eman is zyx

My current output is:

Ym eman s1 zyx

I am not able to achieve my desired output.Don't know what I am doing wrong here

Here is my code

    char[] sentence = "  Hi my name is person!".toCharArray();
    System.out.println(ReverseSentence(sentence));

}
private static char[] ReverseSentence(char[] sentence)
{
    //Given: "Hi my name is person!"
    //produce: "iH ym eman si !nosrep"

    if(sentence == null) return null;
    if(sentence.length == 1) return sentence;

    int startPosition=0;
    int counter = 0;
    int sentenceLength = sentence.length-1;

    //Solution handles any amount of spaces before, between words etc...

    while(counter <= sentenceLength)
    {
        if(sentence[counter] == ' ' && startPosition != -1 || sentenceLength == counter) //Have passed over a word so upon encountering a space or end of string reverse word
        {
            //swap from startPos to counter - 1
            //set start position to -1 and increment counter
            int begin = startPosition;

            int end;
            if(sentenceLength == counter)
            {
                end = counter;
            }
            else
                end = counter -1;
            char tmp;

            //Reverse characters
            while(end >= begin){

                tmp = sentence[begin];
                sentence[begin] = sentence[end];
                sentence[end] = tmp;

                end--; begin++;

            }

            startPosition = -1; //flag used to indicate we have no encountered a character of a string


        }

        else if(sentence[counter] !=' ' && startPosition == -1) //first time you encounter a letter in a word set the start position
        {
            startPosition = counter;
        }

        counter++;
    }

    return sentence;
}

Upvotes: 0

Views: 9943

Answers (7)

jagdeesh kumar
jagdeesh kumar

Reputation: 1

import java.util.Scanner;

public class Reverse_alternate_word {
    public static String reverseWord(String str){  // input :  my name is rohit
        char ch;                                   // output : my eman is tihor
        String rev="";

        for(int i=0; i<str.length(); i++){
             ch = str.charAt(i);
             rev =ch + rev;
        }
        return  rev;
    }
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        String sentence=sc.nextLine();

        int count = 0;
        String arr[] = sentence.split(" ");
        for(int i=0; i< arr.length; i++)
        {
            if(i%2==1){
               String rev_word= reverseWord(arr[i]);
                System.out.print(rev_word+" ");
            }else{
                System.out.print(arr[i]+" ");
            }
        }
    }
}

Upvotes: 0

rushikesh sarolkar
rushikesh sarolkar

Reputation: 1

//reverse second word of sentence in java public class ReverseSecondWord {

public static void main(String[] args) {
    
    String s="hello how are you?";
    String str[]=s.split(" ");
    String rev="";
    
    for(int i=0;i<str[1].length();i++)
    {
    char ch=str[1].charAt(i);
    rev=ch+rev;
    }       
    str[1]=rev;     
    for(int i=0;i<str.length;i++)
    {
        System.out.print(str[i]+" ");
    }
}

}

Upvotes: 0

Jaswanth Harsha
Jaswanth Harsha

Reputation: 1

package com.eg.str;

// Without using StringBuilder  
// INPUT: "Java is very cool prog lang"
// OUTPUT: Java si very looc prog gnal

public class StrRev {
    
    public void reverse(String str) {
        String[] tokens = str.split(" ");
        String result = "";
        String k = "";
        for(int i=0; i<tokens.length; i++) {
            if(i%2 == 0)
                System.out.print(" " + tokens[i] + " ");
            else
                result = tokens[i];
                
                for (int j = result.length()-1; j >= 0; j--)  {
                    k = "" + result.charAt(j);
                    System.out.print(k);
                }
                result = "";
        }   
    }
    
    

    public static void main(String[] args) {
        
        StrRev obj = new StrRev();
        obj.reverse("Java is very cool prog lang");
    }
}

Upvotes: 0

Tagir Valeev
Tagir Valeev

Reputation: 100269

Just for completeness here's Java-8 solution:

public static String reverseSentence(String input) {
    String[] words = input.split(" ");
    return IntStream.range(0, words.length)
            .mapToObj( i -> i % 2 == 0 ? words[i] : 
                    new StringBuilder(words[i]).reverse().toString())
            .collect(Collectors.joining(" "));
}

reverseSentence("My name is xyz"); // -> My eman is zyx

Upvotes: 0

AnkeyNigam
AnkeyNigam

Reputation: 2820

If you want to reverse the alternate word you can try something like splitting the whole String into words delimited by whitespaces and apply StringBuilder reverse() on every second word like :-

        String s = "My name is xyz";
        String[] wordsArr = s.split(" "); // broke string into array delimited by " " whitespace
        StringBuilder sb = new StringBuilder();
        for(int i = 0 ; i< wordsArr.length; i++){ // loop over array length
            if(i%2 == 0) // if 1st word, 3rd word, 5th word..and so on words 
                sb.append(wordsArr[i]); // add  the word as it is
            else sb.append(new StringBuilder(wordsArr[i]).reverse()); // else use StringBuilder revrese() to reverse it
            sb.append(" ");// add a whitespace in between words
        }
        System.out.println(sb.toString().trim()); //remove extra whitespace from the end and convert StringBuilder to String

Output :- My eman is zyx

Upvotes: 2

mazhar islam
mazhar islam

Reputation: 5619

You can solve your problem vary easy way! Just use a flag variable which will indicate the even or odd position, more precisely whether any word will gonna be reversed or not!

Look at the following modification I made in your code, just added three extra line:

private static boolean flag = true;// added a variable flag to check if we reverse the word or not.
private static char[] ReverseSentence(char[] sentence)
{
    //Given: "Hi my name is person!"
    //produce: "iH ym eman si !nosrep"

    if(sentence == null) return null;
    if(sentence.length == 1) return sentence;

    int startPosition=0;
    int counter = 0;
    int sentenceLength = sentence.length-1;

    //Solution handles any amount of spaces before, between words etc...

    while(counter <= sentenceLength)
    {
        if(sentence[counter] == ' ' && startPosition != -1 || sentenceLength == counter) //Have passed over a word so upon encountering a space or end of string reverse word
        {
            flag = !flag; // first time (odd position) we are not going to reverse!
            //swap from startPos to counter - 1
            //set start position to -1 and increment counter
            int begin = startPosition;

            int end;
            if(sentenceLength == counter)
            {
                end = counter;
            }
            else
                end = counter -1;
            char tmp;

            //Reverse characters
            while(end >= begin & flag){ //lets see whether we are going to reverse or not

                tmp = sentence[begin];
                sentence[begin] = sentence[end];
                sentence[end] = tmp;

                end--; begin++;

            }

            startPosition = -1; //flag used to indicate we have no encountered a character of a string


        }

        else if(sentence[counter] !=' ' && startPosition == -1) //first time you encounter a letter in a word set the start position
        {
            startPosition = counter;
        }

        counter++;
    }

    return sentence;
}

Input

My name is xyz

Output:

My eman is zyx

Upvotes: 0

Nir Alfasi
Nir Alfasi

Reputation: 53535

The following code does this "special reverse" which reverses any other word in the sentence:

public static void main(String[] args) {
    String sentence = "My name is xyz";
    System.out.println(specialReverse(sentence)); //  My eman is zyx
}

private static String specialReverse(String sentence) {
    String result = "";
    String[] words = sentence.split(" ");
    // we'll reverse only every second word according to even/odd index
    for (int i = 0; i < words.length; i++) {
        if (i % 2 == 1) {
            result += " " + reverse(words[i]);
        } else {
            result += " " + words[i];
        }
    }
    return result;
}

// easiest way to reverse a string in Java in a "one-liner"
private static String reverse(String word) {
    return new StringBuilder(word).reverse().toString();
}

Upvotes: 0

Related Questions