
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to Split a String into a Number of Substrings in Java
String splitting is the act of dividing a string into smaller parts using a specific delimiter. This helps in handling sections of the string separately. The following are the different methods in Java to split a string into a number of substrings
Using the string split() method
Using the string split() method with whitespace
Split string using split() method
The string split method divides a string into substrings based on a delimiter, returning an array of these substrings for further use.
Example
The following example splits a string into a number of substrings with the help of str split(string) method and then prints the substrings.
public class JavaStringSplitEmp{ public static void main(String args[]) { String str = "jan-feb-march"; String[] temp; String delimeter = "-"; temp = str.split(delimeter); for(int i = 0; iOutput
jan feb march jan jan feb.march feb.march jan feb.marchSplit string using split() method with whitespace
We will know how to split a string using whitespace as the delimiter. The split method, with the delimiter separating the string wherever a space appears, gives an array of substrings that are printed one by one.
Example
The following example splits a string into a number of substrings using the split Method with Whitespace
public class HelloWorld { public static void main(String args[]) { String s1 = "t u t o r i a l s"; String[] words = s1.split("\\s"); for(String w:words) { System.out.println(w); } } }Output
t u t o r i a l sjava_strings.htm