Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flip two words in a string, Java

So say I have a string called x that = "Hello world". I want to somehow make it so that it will flip those two words and instead display "world Hello". I am not very good with loops or arrays and obviously am a beginner. Could I accomplish this somehow by splitting my string? If so, how? If not, how could I do this? Help would be appreciated, thanks!

like image 834
Lanuk Hahs Avatar asked Feb 28 '26 17:02

Lanuk Hahs


2 Answers

1) split string into String array on space.

String myArray[] = x.split(" ");

2) Create new string with words in reverse order from array.

String newString = myArray[1] + " " + myArray[0];

Bonus points for using a StringBuilder instead of concatenation.

like image 186
Brian Roach Avatar answered Mar 03 '26 13:03

Brian Roach


String abc = "Hello world";
String cba = abc.replace( "Hello world", "world Hello" );

abc = "This is a longer string. Hello world. My String";
cba = abc.replace( "Hello world", "world Hello" );

If you want, you can explode your string as well:

String[] pieces = abc.split(" ");
for( int i=0; i<pieces.length-1; ++i )
    if( pieces[i]=="Hello" && pieces[i+1]=="world" ) swap(pieces[i], pieces[i+1]);

There are many other ways you can do it too. Be careful for capitalization. You can use .toUpperCase() in your if statements and then make your matching conditionals uppercase, but leave the results with their original capitalization, etc.

like image 42
Authman Apatira Avatar answered Mar 03 '26 11:03

Authman Apatira