Reverse a string using byte array in Java
This post will discuss how to reverse a string in Java using a byte array.
A byte array is an array of bytes, which are the smallest units of data that can be stored in a computer. A simple way to reverse a string using a byte array is to use the String.getBytes() method of the String class, which returns a byte array representation of the string using the specified charset. Then, we can swap the bytes in the array in-place, by using two pointers that start from the two ends of the array and move towards each other until they meet. Finally, convert the reversed byte array back into a string using the String(byte[]) constructor or any other method that can decode bytes into characters. Here is an example of reversing a string using a byte array in Java:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import java.util.Arrays; class Main { // Method to reverse a string in Java using a byte array public static String reverse(String str) { // return if the string is null or empty if (str == null || str.equals("")) { return str; } // convert string into bytes byte[] bytes = str.getBytes(); // start from the two endpoints `l` and `h` of the given string // and increment `l` and decrement `h` at each iteration of the loop // until two endpoints intersect (l >= h) for (int l = 0, h = str.length() - 1; l < h; l++, h--) { // swap values at `l` and `h` byte temp = bytes[l]; bytes[l] = bytes[h]; bytes[h] = temp; } // convert byte array back into a string return new String(bytes); } public static void main(String[] args) { String str = "Reverse me!"; // String is immutable str = reverse(str); System.out.println("The reversed string is " + str); // "!em esreveR" } } |
We can also create a new byte array with the same length as the original one, and copy the bytes from the original array to the new one in reverse order. However, this requires extra space and may not be preferred approach. That’s all about reversing a string in Java using a byte array.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)