Avatar of Radhika Sinha
Radhika Sinha
 asked on

how to swap alternative words in a string

ex:
i/p:  this is the first good java prog
o/p: prog java  good first the is  this.
Java

Avatar of undefined
Last Comment
krakatoa

8/22/2022 - Mon
Pawan Kumar

Please try this solution
 public static void main(String args[])
    {
        String inputstring = "this is the first good java prog"; /*Input string*/
        String[] splitter = inputstring.split(" "); /*Split the string using space*/
        String ReverseString = ""; /*Set the result reverse string to blank*/
        for (int looper = splitter.length - 1; looper >= 0; looper--) 
        {
          ReverseString += (splitter[looper] + " ");
        }
        System.out.println(ReverseString.trim()); /*Print the output - Reverse string*/    
    } 

Open in new window


OUTPUT
prog java good first the is this

Open in new window


ref1
or you can also refer this Ref-http://www.geeksforgeeks.org/reverse-words-in-a-given-string/
Radhika Sinha

ASKER
thanks ...but can you do it without any builtin methods
Pawan Kumar

Which built in methods you are talking about. Split?
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Radhika Sinha

ASKER
yes!!
split and trim both
Pawan Kumar

We can do that but that will again take lot of efforts and will be slow as compared to functions provided by Java.
awking00

>>thanks ...but can you do it without any builtin methods<<
>>yes!!
 split and trim both
<<
It can't be done without using ANY built-in methods, but it can be done without using split and trim using indexes and substrings. What built-in methods can you use?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
krakatoa

As an observation, your question is not going to be answered by anything that appears here in this thread, except by accident, since your question, which is, partly : "how to swap alternative words" would be wrong (even if it were right in the first place) according to the example output you require, because to swap "alternative" words, we would need you to tell us what those alternatives were so as to be able to swap them. On the other hand, if you meant "alternate" words, then each word would change position with its neighbour - another scenario with which your ambitions do not chime.

But as usual, badly worded questions (which put all the onus on unravelling their hidden meanings on the Experts), become bones of contention, over which endless arguments ensue, wasting everyone's time, usually for no ultimate reward, as they are invariably abandoned and bring the tone, mood and usefulness of the whole TA down.

So having said all that, here is a bit of code that you can put some more effort into, and improve to get rid of the ugly spatial insertion used as an artefact to avoid the pain of the better, alternative algorithm that is for you and others to discover.

class Backwards {

 public static void main(String[] args){

  String s = "this is the first good java prog";
  String s1 = "";
  String s2 = "";
  

  for(int y=s.length()-1;y>-1;y--){
  
        s1 += s.charAt(y);
  }

  s1 += " ";
  
  int blankpointer = s1.indexOf(" ");
  int downpointer = blankpointer-1;

    while(s2.length()<s1.length()-1){
    
        s2 += s1.charAt(downpointer);
          
        if(s2.length()==blankpointer){
                
                blankpointer = s1.indexOf(" ",blankpointer+1);
                downpointer = blankpointer;
                continue;
                
        }
        downpointer--;
    }
    
    System.out.println(s);
    System.out.println(s1);
    System.out.println(s2);
 }

}

Open in new window

krakatoa

I prefer this version now :

class Backwards {

 public static void main(String[] args){

 
 String s = "The Fall 3 Now the serpent was more crafty than any of the wild animals the Lord God had made. He said to the woman, Did God really say, You must not eat from any tree in the garden? 2 The woman said to the serpent, We may eat fruit from the trees in the garden, 3 but God did say, You must not eat fruit from the tree that is in the middle of the garden, and you must not touch it, or you will die. 4 You will not certainly die, the serpent said to the woman. 5 For God knows that when you eat from it your eyes will be opened, and you will be like God, knowing good and evil. 6 When the woman saw that the fruit of the tree was good for food and pleasing to the eye, and also desirable for gaining wisdom, she took some and ate it. She also gave some to her husband, who was with her, and he ate it. 7 Then the eyes of both of them were opened, and they realized they were naked; so they sewed fig leaves together and made coverings for themselves.";
 
 
  //String s = "this is the first good java prog";
  String s1 = "";
  String s2 = "";
  boolean blankcount = false;
  

  for(int y=s.length()-1;y>-1;y--){
  
        s1 += s.charAt(y);
  }
  
  int blankpointer = s1.indexOf(" ");
  int downpointer = blankpointer-1;

    while(!(s2.length() == s1.length()-1)){
    
        s2 += s1.charAt(downpointer);
          
        if(s2.length() == blankpointer){
                
                blankpointer = s1.indexOf(" ",blankpointer+1);
                if(blankcount){s2 = s2.substring(0,s1.lastIndexOf(" "))+" "+s.substring(0,s.indexOf(" "));break;}
                if(blankpointer == s1.lastIndexOf(" ")){blankcount = true;}
                downpointer = blankpointer;
                continue;
                
        }
        downpointer--;
    }
    
    System.out.println(s+"\n");
    System.out.println(s1+"\n");
    System.out.println(s2+"\n");
 }

}

Open in new window

krakatoa

Here is a shorter version moving individual words :

class MoveBackWordsToFront {

 public static void main(String[] args){

 
 //String s = "The Fall 3 Now the serpent was more crafty than any of the wild animals the Lord God had made. He said to the woman, Did God really say, You must not eat from any tree in the garden? 2 The woman said to the serpent, We may eat fruit from the trees in the garden, 3 but God did say, You must not eat fruit from the tree that is in the middle of the garden, and you must not touch it, or you will die. 4 You will not certainly die, the serpent said to the woman. 5 For God knows that when you eat from it your eyes will be opened, and you will be like God, knowing good and evil. 6 When the woman saw that the fruit of the tree was good for food and pleasing to the eye, and also desirable for gaining wisdom, she took some and ate it. She also gave some to her husband, who was with her, and he ate it. 7 Then the eyes of both of them were opened, and they realized they were naked; so they sewed fig leaves together and made coverings for themselves.";
 
 
  String s = "this is the first good java prog";
  String s1 = "";
  int lastblank = s.lastIndexOf(" ");
  int tempblank = lastblank;
  int movingblank = 0;

  while(s1.length()<s.length()){
  
        if(tempblank == lastblank){s1 += s.substring(tempblank+1,s.length())+" ";}
        movingblank = (s.substring(0,lastblank-1)).lastIndexOf(" ");
        s1 += s.substring(movingblank+1,lastblank)+" ";
        lastblank = movingblank;
  }
  
  System.out.println(s1);
  
 }

}

Open in new window

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ASKER CERTIFIED SOLUTION
krakatoa

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
awking00

Radhika Sinha,
Given your example, it appears that your question is actually, "How can I create a new string that reverses the order of the words in a given string?" If that is what you really want, please respond to the experts and, if not, please respond with a more detailed explanation (perhaps with more examples) of what you need.
krakatoa

Answered by krakatoa in line with the  Asker's requirements.