Strings and Arrays
![]() |
Strings & Arrays in Java: Splitting, Sorting & Reversing |
Introduction
In earlier lessons, we learned about Strings, Arrays, ArrayLists, and other operations on them.
In this unit, we will learn some more operations concerning Strings, Arrays, and ArrayLists and also how they can be used in combination.
1. Splitting Strings
String splitting in Java resembles Python string splitting.
The split() method splits a string from the specified separator and returns an array of substrings.
Syntax
str.split(separator);
String is split at the separator
Whitespace as Separator
Whitespace is passed as an argument for the separator. It splits the string into substrings on every occurrence of whitespace. For example, it splits a sentence into words.
Here also, whitespace is passed as an argument to the split() method. It splits the string into tokens at every occurrence of the given argument, that is, whitespace.
Syntax
str.split(" ");
Code:
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String message = "See You Soon";
String[] messageArr = message.split(" ");
System.out.println(Arrays.toString(messageArr));
}
}
Output:
[See, you, soon]
So the above code splits the message string at every occurrence of whitespace and stores the substrings in messageArr.
String as Separator
A string can also be used as a separator in the split() method.
Syntax
str1.split(str2);
code:
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String message = "See--you--soon";
String[] messageArr = message.split("--");
System.out.println(Arrays.toString(messageArr));
}
}
Output:
[See, you, soon]
So the above code passes the string "--" as an argument to the split() method, thereby splitting the string at every occurrence of "--".
2. Strings Splitting using Regex
Regex stands for Regular Expressions and is a sequence of characters defining the search or manipulation pattern of strings.
A regular expression may consist of a single character or a complex expression.
Some Special Characters in Regex:
These are the special characters in Regex:
metacharacter: dot (.)
bracket list: []
position anchors: ^, $
occurrence indicators: +, *, ?, { }
parentheses: ()
or: |
escape and metacharacter: backslash (\)
All other characters other than these special characters are treated as normal characters.
Let's try to understand the operation of the split() method with Regex.
Example:
The Regex pattern [.-.] accepts any one character from the range specified, and + means one or more instances of a character or regex pattern.
For example, [0-9]+ will match one or more digits.
Code
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String str = "One1Two22Three333Four";
String[] stringArr = str.split("[0-9]+");
System.out.println(Arrays.toString(stringArr));
}
}
Output:
[One, Two, Three, Four]
It can be seen that the split() method, in the above example, has split a string at every occurrence of a digit or group of digits.
There may be some special characters in regex that we need to use as delimiters.
Let's attempt to split some strings with the character + above.
Example
Code
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String message = "See+you+soon";
String[] messageArr = message.split("+");
System.out.println(Arrays.toString(messageArr));
}
}
Output:
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
+
^
In the above example, this leads to the error.
This happens because the character + has a special meaning in regex: it matches one or more occurrences. Since there is no pattern or character supplied, the split() method does not know what to match.
3. RegEx Special Characters to Split Strings
The split() method interprets all strings passed as arguments as Regex.
To use these special characters in the split() method, we have to escape their special meaning so that they can be compared with normal characters. This is done by prefixing the special regex character with \\.
In Regex, \\ is treated as an escape sequence meaning that it nullifies the special meaning of the next character.
So, any regex special characters that will be used will need escaping with \\. For example, \\+.
Example 1:
Splitting a string based on the + character.
Code
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String message = "See+you+soon";
String[] messageArr = message.split("\\+");
System.out.println(Arrays.toString(messageArr));
}
}
Output:
[See, you, soon]
4. Joining strings
The method join() joins the specified elements with a given delimiter and returns a new string.
Delimiters are those special characters or set of characters that signal the start or end of anything, statement, string, etc.
Joining Strings
In Java joining multiple strings with a delimiter is done with the join() method.
Syntax
String.join(delimiter, string1, string2, ...);
Whereas
delimiter: Joining string for given values
string1, string2: Strings that are to be joined
Code
class Main {
public static void main(String[] args) {
String str1 = "Java";
String str2 = "is a";
String str3 = "Programming";
String str4 = "Language";
System.out.print(String.join(" ", str1, str2, str3, str4)); // joining the strings using join() method
}
}
Output:
Java is a Programming Language
The above code joins four strings, Java, is a, Programming, Language, using the join() method by using white space.
Joining String Arrays
Now in Java, joining the elements from the String Array can be performed using the join() method.
Syntax
String.join(delimiter, arr);
Code:
class Main {
public static void main(String[] args) {
String[] stringArr = {"Java", "is a", "Programming", "Language"};
String result;
result = String.join("-", stringArr);
System.out.println(result);
}
}
Output:
Java-is a-Programming-Language
Joining String ArrayLists
In Java, joining the elements in the String Array List can be performed using the join() method.
Syntax
String.join(delimiter, arrList);
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> stringArrList = new ArrayList<>();
stringArrList.add("Java");
stringArrList.add("is a");
stringArrList.add("Programming");
stringArrList.add("Language");
String result;
result = String.join("-", stringArrList);
System.out.println(result);
}
}
Output:
Java-is a-Programming-Language
5. Sorting Arrays
We can sort an Array using the Arrays.sort() method.
There are two ways of sorting:
Ascending Order
Descending Order
This method modifies the original Array and sorts it according to the given condition.
Ascending Order
Here we shall consider sorting an Array in ascending order.
Syntax
Arrays.sort(arr);
Code:
import java.util.*;
class Main {
public static void main(String[] args) {
int[] arr = {3, 1, 2, 5, 4};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
Output:
[1, 2, 3, 4, 5]
Descending Order
The descending sort is achieved by passing Collections.reverseOrder() to the Arrays.sort() method.
Because we are using a method from the Collections class, we cannot use it for primitive data types (like int, float, etc.) and must use their corresponding wrapper classes (like Integer, Float, etc.).
Syntax
Arrays.sort(arr, Collections.reverseOrder());
Code:
import java.util.*;
class Main {
public static void main(String[] args) {
Integer[] arr = {3, 1, 2, 5, 4};
Arrays.sort(arr, Collections.reverseOrder());
System.out.println(Arrays.toString(arr));
}
}
Output:
[5, 4, 3, 2, 1]
6. Reversing Sequences
Reversing Strings
A string value is reversed by first converting it into a character array and then traversing it in reverse order.
We can use the toCharArray() string method to get a character array from a string.
Syntax
str.toCharArray();
Here, the str is a string.
Code
import java.util.*;
class Main {
public static void main(String[] args) {
String str= "Ramkumar";
char ch[] = str.toCharArray();
String rev = "";
for (int i = ch.length -1; i >= 0; i --){
rev+= ch[i];
}
System.out.println("Original: " + str);
System.out.println("Reversed: " + rev);
}
}
Output:
Original: Ramkumar
Reversed: ramukmar
Flipping Arrays
An array can be reversed by either of the following means:
Using the method Collections.reverse();
Using loop for reversal.
Using the Collections.reverse() Method
The method Collections.reverse reverses the elements of the array passed as a parameter to this method.
Through the Collections class, we can not use primitive data types such as int, float, and so on, but need to use their wrapper classes such as Integer, Float, etc.
To apply the Collections.reverse() method, it will need to convert the array into an ArrayList.
We can use the Arrays.asList() method to convert the Array into an ArrayList then pass it to the Collections.reverse() method. It will make the changes to the ArrayList that will also reflect in the Array.
Syntax: Collections.reverse(Arrays.asList(arr)).
Code:
import java.util.*;
class Main {
public static void main(String[] args){
Integer[] arr = {3, 30, 8, 24};
System.out.println("Original Array: " + Arrays.toString(arr));
Collections.reverse(Arrays.asList(arr)); // reversing the elements of the array
System.out.println("Reversed Array: " + Arrays.toString(arr));
}
}
Output:
Original Array: [3, 30, 8, 24]
Reversed Array: [24, 8, 30, 3
By Loops
We can also use loops to reverse the arrays. Let us consider an example using a for loop.
Code
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
int[] rev = new int[arr.length];
for (int i = 0; i <= arr.length - 1; i++) {
rev[arr.length -1 -i ] = arr[i];
}
System.out.println("Original: " + Arrays.toString(arr) );
System.out.print("Reversed: " + Arrays.toString(rev) );
}
}
Output:
Original: [1, 2, 3, 4, 5]
Reversed: [5, 4, 3, 2, 1]
Reversing ArrayList
An ArrayList can be reversed using the Collections.reverse() method.
This will modify the ArrayList and reverse the data inside.
Syntax
Collections.reverse(arrList);
Code:
import java.util.*;
class Main {
public static void main(String[] args){
ArrayList<Integer> arrList = new ArrayList<>();
arrList.add(1);
arrList.add(2);
arrList.add(3);
arrList.add(4);
System.out.print("Original ArrayList: ");
System.out.println(arrList);
Collections.reverse(arrList); // reversing the elements of the ArrayList
System.out.print("Reversed ArrayList: ");
System.out.println(arrList);
}
}
Output:
Original ArrayList: [1, 2, 3, 4]
Reversed ArrayList: [4, 3, 2, 1]
Summary
methods of string:
split() : It divides a string at the specified separation point and returns an array of substrings. In order to use special characters such as ^, *, +, etc., as separators, we must escape those characters with "\\".
join() : This joins the given elements with the delimiter specified and returns a new string. It can be used to join strings, string arrays and string ArrayLists.
Sorting Array:
Arrays.sort: sorts the array in ascending order
Arrays.sort(arr, Collections.reverseOrder()): sorts an array in descending order.
Reversal of Sequences:
Reverse a String Value by converting the String to a character array and running it through a loop in REVERSE order. Two ways are there to reverse an array: Using collections. reverse() and Reversing by using loop
An ArrayList may also be reversed with the help of the Collections.reverse() method.