How to swap the positions of Java strings in front and back?
To switch the positions of the beginning and end of a Java string, you can use the substring method and string concatenation.
The specific steps are as follows:
- Firstly, you can obtain the length of a string by using the length() method.
- Using the substring method, obtain the first half and second half of the string separately. The starting position for the first half is 0, and the ending position is half of the string’s length; the starting position for the second half is the string’s length divided by two, and the ending position is the length of the string.
- Concatenate the first half and the second half to get the string after swapping positions.
Here is the sample code:
public class Main {
public static void main(String[] args) {
String str = "Hello World!";
int length = str.length();
String front = str.substring(0, length / 2);
String back = str.substring(length / 2, length);
String result = back + front;
System.out.println(result);
}
}
The code above will output: “World!Hello “
Please note that Java strings are immutable, therefore the operations above will not change the original string’s value but instead return a new string. If you want to modify the original string, you can use the StringBuilder or StringBuffer class for operations.