The methods String[] split(String regex) and String[] split(String regex, int limit) use the passed-in regular expression to split the strings into substrings. We do not explain regular expressions in this book. However, there is a very simple one that is easy to use even if you know nothing about regular expressions: if you just pass into this method any symbol or substring present in a string, the string will be broken (split) into parts separated by the passed-in value, for example:
String[] substrings = "Introduction".split("o");
System.out.println(Arrays.toString(substrings));
//prints: [Intr, ducti, n]
substrings = "Introduction".split("duct");
System.out.println(Arrays.toString(substrings));
//prints: [Intro, ion]
This code just illustrates the functionality. But the following code snippet is more practical:
String s = "There is a bear in the woods";
String[] arr = s.split(" ");
System.out.println(Arrays.toString(arr));
//prints: [There, is, a, bear, in, the, woods]
arr = s.split(" ", 3);
System.out.println(Arrays.toString(arr));
//prints: [There, is, a bear in the woods]
As you can see, the second parameter in the split() method limits the number of resulting substrings.
The method String concat(String str) adds the passed-in value to the end of the string:
String s1 = "There is a bear";
String s2 = " in the woods";
String s = s1.concat(s2);
System.out.println(s); //prints: There is a bear in the woods
The concat() method creates a new String value with the result of concatenation, so it is quite economical. But if you need to add (concatenate) many values, using StringBuilder (or StringBuffer, if you need protection from concurrent access) would be a better choice. We discussed it in the previous section. Another option would be to use the operator +:
String s = s1 + s2;
System.out.println(s); //prints: There is a bear in the woods
The operator +, when used with String values, is implemented based on StringBuilder, so allows the addition of String values by modifying the existing one. There is no performance difference between using StringBuilder and just the operator + for adding String values.
The methods String join(CharSequence delimiter, CharSequence... elements) and String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) are based on StringBuilder too. They assemble the provided values in one String value using the passed-in delimiter to separate the assembled values inside the created String result. Here is an example:
s = String.join(" ", "There", "is", "a", "bear", "in", "the", "woods");
System.out.println(s); //prints: There is a bear in the woods
List<String> list =
List.of("There", "is", "a", "bear", "in", "the", "woods");
s = String.join(" ", list);
System.out.println(s); //prints: There is a bear in the woods