How To Split A String Into Substrings in Java

Chapter: String Handling Last Updated: 22-08-2023 17:12:00 UTC

Program:

            /* ............... START ............... */
                

public class StringSplitExample {
    public static void main(String[] args) {
        String input = "Hello,World,Java";
        String[] parts = input.split(",");

        for (String part : parts) {
            System.out.println(part);
        }
    }
}


// another program for splitting 

public class ComplexSplitExample {
    public static void main(String[] args) {
        String input = "apple orange;banana|grape";
        String[] parts = input.split("[,;|]");

        for (String part : parts) {
            System.out.println(part);
        }
    }
}

                /* ............... END ............... */
        

Notes:

  • In first example, the string "Hello,World,Java" is split using the comma , as the delimiter. The resulting array parts will contain three elements: "Hello", "World", and "Java", which are then printed using a loop.
  • In second example, the regular expression [,;|] specifies that the string should be split at commas, semicolons, or pipe symbols, resulting in four substrings: "apple", "orange", "banana", and "grape".
  • Keep in mind that the split() method uses regular expressions, so if your delimiter contains special characters that are also used in regular expressions, you might need to escape those characters appropriately.

Tags

How to split a string into substrings in java #Java split string by space #How to split a string into substrings in java example

Similar Programs Chapter Last Updated
How To Check If A String Contains A Particular Substring In Java String Handling 22-08-2023
How To Remove A Substring From A String Java String Handling 22-08-2023
Java Program To Remove Repeated Characters In A String String Handling 15-08-2023
Java Code To Check If String Contains Specific Characters String Handling 03-06-2023
How To Count The Number Of Cccurrences Of Each Character In A String In Java String Handling 03-06-2023
Java Program To Replace A Character In A String String Handling 03-06-2023
Java Program To Split A String String Handling 03-06-2023
String Length Implementation Java String Handling 02-12-2019

1