How do we split a string with any whitespace chars as delimiters using java?


The split() method of the String class accepts a delimiter (in the form of the string), divides the current String into smaller strings based on the delimiter and returns the resulting strings as an array. If the String does not contain the specified delimiter this method returns an array which contains only the current string.

If the String does not contain the specified delimiter this method returns an array containing the whole string as element.

Splitting the string with white space as delimiter

To split a String into an array of strings with white pace as delimiter −

  • Read the source string.

  • Invoke split() method by passing “ ” as a delimiter.

  • Print the resultant array.

Example

Following Java program reads the contents of a file into a Sting and splits it using the split() method with white space as delimiter −

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class SplitExample {
   public static void main(String args[]) throws FileNotFoundException {
      Scanner sc = new Scanner(new File("D:\\sample.txt"));
      StringBuffer sb = new StringBuffer();
      String input = new String();
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         sb.append(input);
      }
      String source = sb.toString();
      String result[] = source.split(" ");
      for(int i = 0; i < result.length; i++) {
         System.out.println(result[i]);
      }
   }
}

Output

Hello
how
are
you
raja
Published on 10-Oct-2019 10:09:09
Advertisements