How to split String into String
Let's say we have a task to split a sentence into an array of words. In this case, we can either
append until we encounter a space character (
" "), or we can use the
split() method is a
String method that takes a
regex as a parameter. What is
Regex stands for regular expression, which is essentially a character or set of characters that we use to split our string. We can input a space character
" " in the regex, and then our sentence will be divided into words.
Let's take a look at an example:
Here we have split the string into an array of words. We used
" " to indicate to the program that it should split the sentence at each occurrence of
How to split a String by a specific character
We can also split our string using any other character. For example, let's split the link at the occurrence of the character
We have split the URL into separate parts at each occurrence of the
"/" character, and now we can see each element of the URL. In other words, when we split the string at the
"/" character, we obtained an array of strings.
You may also notice that the method removes the specified character from the resulting array when splitting.
How to split a String into characters with String type
To split a string into an array at each occurrence of a single character, we can simply use empty quotation marks
"" as the parameter. Let's take a look at an example:
We have split the string into individual letters. You might think that there is a specific method for this, like
toCharArray(), but the difference is that when using the
split() method, we obtain an array of elements of type
String, whereas with
toCharArray(), we directly obtain an array of elements of type
What will be the result of this code?
Select the correct answer
Everything was clear?