简体   繁体   中英

java swap last and 1st strings - problem works for 3 but not for 4

The code below works when number of strings in array is odd (3,5,7) however it does not work when the number is even. For example, if I use "my is the name" I get output

name is the name

public void randomTest() {
       String str ="my is name";
       //Step1: split so that I can get them in in array
       String [] arrStr= str.split(" ");
       for(int i=0;i<arrStr.length;i++){
           //Step2: Using temp swap 1st and last 
           String temp = arrStr[0];
           arrStr[0] = arrStr[arrStr.length-1];
           arrStr[arrStr.length-1] = temp;

           System.out.print(arrStr[i]+" ");
       }
    }

Any idea how can I make it work for even number of Strings? Thank You.

Since Arvind Kumar Avinash has shared the fixed solution, I just like to offer an alternative option: After splitting the string into String array, maybe you can simply swap the last and first values, and then join them together:

String str ="my is the name";

// split
String[] arrStr= str.split(" ");

// swap
String temp = arrStr[0];
arrStr[0] = arrStr[arrStr.length - 1];
arrStr[arrStr.length - 1] = temp;

// join them back
str = String.join(" ", arrStr);

System.out.println(str); // name is the my

You need to iterate the loop only for half of the length of the array ie

for (int i = 0; i < arrStr.length / 2; i++)

Also, you need to use the counter variable, i instead of the fixed values 0 and 1 . Make sure to limit the indices in the range of 0 to length_of_array - 1 which is the range of indices of an array in Java.

Do it as follows:

public class Main {
    public static void main(String[] args) {
        String str = "my is the name";
        String[] arrStr = str.split(" ");

        // Swap the elements of the array
        for (int i = 0; i < arrStr.length / 2; i++) {
            String temp = arrStr[i];
            arrStr[i] = arrStr[arrStr.length - i - 1];
            arrStr[arrStr.length - i - 1] = temp;
        }

        // Display the array
        for (int i = 0; i < arrStr.length; i++) {
            System.out.print(arrStr[i] + " ");
        }
    }
}

Output:

name the is my 

If you want to swap only the first word with the last word, you do not need a loop. You can simply so it as follows:

public class Main {
    public static void main(String[] args) {
        String str = "my is the name";
        String[] arrStr = str.split(" ");

        // Swap the first and the last words
        String temp = arrStr[0];
        arrStr[0] = arrStr[arrStr.length - 1];
        arrStr[arrStr.length - 1] = temp;

        // Display the array
        for (int i = 0; i < arrStr.length; i++) {
            System.out.print(arrStr[i] + " ");
        }
    }
}

Output:

name is the my 

What you are currently doing is swapping the first and last elements n times, where n is the size of the array. This makes it so that when you have an even number of elements, for example, 2, then you are swapping the first and last elements, and then swapping them back to their original position, which is unswapped. This is also why it is working for an odd number of elements since you are swapping the first and last elements an even number of times and then once more. If you just want to swap the first and last elements, you can simply get rid of the for loop that you have and it will work properly.

    public void randomTest() {
       String str ="my is name";
       //Step1: split so that I can get them in in array
       String [] arrStr= str.split(" ");
       
       //Step2: Using temp swap 1st and last 
       String temp = arrStr[0];
       arrStr[0] = arrStr[arrStr.length-1];
       arrStr[arrStr.length-1] = temp;
    }

Afterwards, if you want to merge the strings back together, you can use

str = String.join(" ", arrStr);

or a StringBuilder object like so.

StringBuilder sb = new StringBuilder(arrStr[0]);
for (int i = 0; i < arrStr.length; i++) {
    sb.append(" ").append(arrStr[i]);
}
str = sb.toString();

The effect of either of these will turn my name is foo into foo name is my , basically swapping the first and last words, and will work for a string with any length or number of words.

Easiest way is to substring first and last word from the sentence.

    int first = name.indexOf(' ');                             // first "space" character that occurs
    int last = name.lastIndexOf(' ');                          // last "space" character that occurs

    String firstWord = name.substring(0, first);               // substring first word from index 0  to index of first "space" character
    String lastWord = name.substring(last, name.length()-1);   // substring last word from index the of last "space" character to higher index o sentence
    String midSentece = name.substring(first, last);           // substring rest of the sentence

    System.out.println(lastWord + midSentece + firstWord);
   

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