Basic String Manipulation in Java
Lesson Overview
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.
Tokenizing a String in Java
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:
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:
In the example above, StringTokenizer is used to split the sentence into tokens using space as the delimiter.
Exploring String Concatenation
In Java, the + operator, the StringBuilder.append method, or streams can be used to concatenate strings into a larger string:
Using the + Operator:
Using StringBuilder.append:
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:
In the example above:
- ArrayList Initialization: We initialize an
ArrayListwith several strings. - Creating a Stream: We call the
stream()method on theArrayListto 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.
