How to split a given String into substrings while specifying a delimiter using Java split() method
Coding River
How to split a given String into substrings while specifying a delimiter using the Java split() method
In this video, we will discuss about the Java split() method, which can be used to split a given String into substrings while specifying a delimiter. One important point to note here is that, this method returns an array of strings and the split() method has two variations
- In the first example, I will show you how to split a given String into substrings and have it return an array of Strings String str1 = "23/05/2020";
Since we are dealing with arrays, I am going to declare an array that will store the returned values whenever the method is executed
String substrings[] = str1.split("/");
"/" here is the delimiter, this means that wherever the method finds this character (/) in the String, it will split the given String at that precise position
Now we need to find a way to output all the values stored in the array Doing a System.out.println(substrings); will not work
We will rather use the Arrays.toString() method, by writing System.out.println(Arrays.toString(substrings));
We could also output each substring at every array index position System.out.println(substrings[0]); System.out.println(substrings[1]); System.out.println(substrings[2]); ...
- In the second example, I will show you how to limit the number of substrings to be returned after splitting a given String
String str1 = "23/05/2020"; Since we are dealing with arrays, I am going to declare an array that will store the returned values whenever the method is executed
String split[] = str1.split("/" , 2);
"/" here is the delimiter, this means that wherever the method finds this / character, it will split the given String at that precise position And 2 represents the limited number of substrings to output. This method, when evaluated, is supposed to return an array of only two Strings even when the delimiter is present in the array more than two times.
Now we need to find a way to output all the values stored in the array Doing a System.out.println(substrings); will not work
We will rather use the Arrays.toString() method, by writing
System.out.println(Arrays.toString(split));
Note that our array contains only two substrings, exactly as we indicated it in the method statement. Also, the delimiter is present in our array more than two times.
#codingriver #java #programming ... https://www.youtube.com/watch?v=q9xpEEZwloE
13887417 Bytes