Search

Thursday, May 25, 2017

How to use "." as delimiter in String.split() method

String.split takes a regex, and '.' has a special meaning for regexes.
You have to use "\" along with "." in arguments like below
String[] words = line.split("\\.");
Some folks seem to be having trouble getting this to work, so here is some runnable code you can use to verify correct behaviour.
TestSplit.java
import java.util.Arrays;

public class TestSplit {
  public static void main(String[] args) {
    String line = "aa.bb.cc.dd";
    String[] words = line.split("\\.");
    System.out.println(Arrays.toString(words));
    // Output is "[aa, bb, cc, dd]"
  }
}

No comments:

Post a Comment

Featured Post

ClassNotFoundException vs. NoClassDefFoundError

This is a very common question in Java interviews. Here we will learn to distinguish between two similar, but different problems that ca...