Welcome! In this lesson, we'll delve into the basic string manipulation features of Java, which include string tokenization, string concatenation, trimming of whitespace from strings, and type conversion operations.
In Java, we can use the split
method from the String
class or the StringTokenizer
class to tokenize a string, essentially splitting it into smaller parts or 'tokens'.
Using split
method:
Java1class Solution { 2 public static void main(String[] args) { 3 String sentence = "Java is an amazing language!"; 4 String[] tokens = sentence.split(" "); 5 6 for (String token : tokens) { 7 System.out.println(token); 8 } 9 } 10}
In the example above, we use a space as a delimiter to split the sentence
into words. This operation will print each word in the sentence on a new line.
Using StringTokenizer
:
Java1import java.util.StringTokenizer; 2 3class Solution { 4 public static void main(String[] args) { 5 String sentence = "Java is an amazing language!"; 6 StringTokenizer tokenizer = new StringTokenizer(sentence, " "); 7 8 while (tokenizer.hasMoreTokens()) { 9 System.out.println(tokenizer.nextToken()); 10 } 11 } 12}
In the example above, StringTokenizer
is used to split the sentence
into tokens using space as the delimiter.
In Java, the +
operator, the StringBuilder.append
method, or streams can be used to concatenate strings into a larger string:
Using the +
Operator:
Java1class Solution { 2 public static void main(String[] args) { 3 String str1 = "Hello,"; 4 String str2 = " World!"; 5 String greeting = str1 + str2; 6 System.out.println(greeting); // Output: "Hello, World!" 7 } 8}
Using StringBuilder.append
:
Java1class Solution { 2 public static void main(String[] args) { 3 String str1 = "Hello,"; 4 String str2 = " World!"; 5 StringBuilder sb = new StringBuilder(str1); 6 sb.append(str2); 7 System.out.println(sb.toString()); // Output: "Hello, World!" 8 } 9}
Using Streams (Java 8+):
Streams in Java provide a powerful way to perform operations on collections, such as filtering, mapping, and reducing. In this context, we can use streams to concatenate strings in an ArrayList
. Here’s how:
Java1import java.util.ArrayList; 2import java.util.Arrays; 3import java.util.stream.Collectors; 4 5class Solution { 6 public static void main(String[] args) { 7 ArrayList<String> strings = new ArrayList<>(Arrays.asList("Hello", " World!", " Java", " Streams!")); 8 String result = strings.stream().collect(Collectors.joining()); 9 System.out.println(result); // Output: "Hello World! Java Streams!" 10 } 11}
In the example above:
- ArrayList Initialization: We initialize an
ArrayList
with several strings. - Creating a Stream: We call the
stream()
method on theArrayList
to create a stream of its elements. It converts the collection into a sequence of elements that supports various methods to perform computations. - Collecting the Stream: We use the
Collectors.joining()
method to concatenate all the elements of the stream into a single string. TheCollectors.joining()
method can also take an optional delimiter as an argument if you need to insert characters (like commas or spaces) between the elements.
In Java, the trim
method can remove both leading and trailing whitespaces from a string:
Java1class Solution { 2 public static void main(String[] args) { 3 String str = " Hello, World! "; // string with leading and trailing spaces 4 str = str.trim(); // remove leading and trailing spaces 5 System.out.println(str); // Output: "Hello, World!" 6 } 7}
In this example, trim
is used to remove leading and trailing whitespaces from a string.
We can convert strings to numbers using methods like Integer.parseInt
(string to integer) and Float.parseFloat
(string to float), and other data types to strings using String.valueOf
:
Java1class Solution { 2 public static void main(String[] args) { 3 String numStr = "123"; 4 int num = Integer.parseInt(numStr); 5 System.out.println(num); // Output: 123 6 7 String floatStr = "3.14"; 8 float pi = Float.parseFloat(floatStr); 9 System.out.println(pi); // Output: 3.14 10 11 int age = 20; 12 String ageStr = String.valueOf(age); 13 System.out.println("I am " + ageStr + " years old."); // Output: I am 20 years old. 14 } 15}
In this code, we use Integer.parseInt
, Float.parseFloat
, and String.valueOf
for type conversions.
In some cases, we may need to combine all the methods discussed:
Java1class Solution { 2 public static void main(String[] args) { 3 String numbers = "1,2,3,4,6"; 4 String[] numArray = numbers.split(","); 5 int sum = 0; 6 7 for (String numStr : numArray) { 8 sum += Integer.parseInt(numStr); 9 } 10 11 float average = (float) sum / numArray.length; 12 System.out.println("The average is " + average); // Output: The average is 3.2 13 } 14}
By integrating these methods, we can transform the string "1,2,3,4,6" into an array of integers, calculate their average, and display the result.
Great job! You've gained an overview of Java's string manipulation features, including string concatenation, string tokenization, trimming whitespace from strings, and type conversions. Now, it's time to get hands-on with these concepts in the exercises that follow. Happy coding!