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:
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.
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
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:
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
:
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:
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!
