How do we split a string on a fixed character sequence in 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.

For example if you pass single space “ ” as a delimiter to this method and try to split a String. This method considers the word between two spaces as one token and returns an array of words (between spaces) in 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 on a fixed character sequence

To split a String into an array of strings each time a particular String occurs −

  • Read the source string.

  • Invoke split() method by passing the desired String 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 another string as a 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(" to ");
      System.out.print(Arrays.toString(result));
   }
}

Output

[Tutorials Point originated from the idea that there exists a class of readers who respond better,
on-line content and prefer, learn new skills at their own pace from the comforts of their drawing rooms.]
raja
Published on 10-Oct-2019 10:36:49
Advertisements