Java String split() method explained
Syntax of split() method
public String[] split(String regex) {}
here, regex means regular expression don't confuse at all you just have to give the string as a parameter to this method.
Example 01 of split() method
public class Split {
public static void main(String[] args) {
String s="hello";
String myarray[]=s.split("e");
for(int i=0;i<myarray.length;i++)
{
System.out.print("element at "+i+" index is "+myarray[i]);
System.out.println();
}
}
}
element at 0 index is h
element at 1 index is llo
import java.util.Arrays;
public class Split {
public static void main(String[] args) {
String s="hello";
String myarray[]=s.split("e");
System.out.println(Arrays.toString(myarray));
}
}
[h, llo]
here, 'h' is basically stored at 0th index and 'llo' is stored at 1th index of the array.
Example 02 of split() method
import java.util.Arrays;
public class Split {
public static void main(String[] args) {
String s="hello technical arbaab";
String myarray[]=s.split(" ");
System.out.println(Arrays.toString(myarray));
}
}
[hello, technical, arbaab]
here, in this example the string "hello technical arbaab" is split from every space and the words are stored at different indexes of an array as you have seen that the string representation of an array shows [hello, technical, arbaab] these are the words stored at 0,1 and 2nd index of an array. If you are finding difficulty in understanding this see below example which works same as this but to get a more clear idea what are the values stored in your array at different indexes.
import java.util.Arrays;
public class Split {
public static void main(String[] args) {
String s="hello technical arbaab";
String myarray[]=s.split(" ");
for(int i=0;i<myarray.length;i++)
{
System.out.println("the value stored at "+i+" index is "+myarray[i]);
System.out.println();//for new line
}
}
}
Output:
the value stored at 0 index is hello
the value stored at 1 index is technical
the value stored at 2 index is arbaab
Imp.note: here one important thing to note is that the character or sequence of character from which you are going to split, that character or sequence of character is not going to store in the array it becomes the target character or target sequence of character to split your string.
Hello, visitor your comments are so helpful for us so do not hesitate just write the comment we read all your comments so don't think your comment goes waste.