Java – How to split a string

To split a string, uses String.split(regex). Review the following examples :


    String phone = "012-3456789";
    String[] output = phone.split("-");
    System.out.println(output[0]);
    System.out.println(output[1]);

Output


    012
    3456789

Note
This split (regex) takes a regex as an argument, remember to escape the regex special characters, like period/dot.

1. Split a Period / dot

The period / dot is a special character in regex, you have to escape it either with a double backlash \\. or uses the Pattern.quote method.

TestSplit.java

package com.mkyong.test

import java.util.regex.Pattern;

public class TestSplit {

    public static void main(String[] args) {

        String test = "abc.def.123";
        String[] output = test.split("\\.");

        //alternative
        //String[] output = test.split(Pattern.quote("."));

        System.out.println(output[0]);
        System.out.println(output[1]);
        System.out.println(output[2]);

    }

}

Output

abc
def
123

Some common checking before split.

TestSplit.java

package com.mkyong.test

import java.util.regex.Pattern;

public class TestSplit {

    public static void main(String[] args) {

        String test = "abc.def.123";
        if(test.contains(".")){
            String[] output = test.split("\\.");
            if(output.length!=3){
                throw new IllegalArgumentException(test + " - invalid format!");
            }else{
                System.out.println(output[0]);
                System.out.println(output[1]);
                System.out.println(output[2]);
            }
        }else{
            throw new IllegalArgumentException(test + " - invalid format!");
        }

    }

}

2. StringTokenizer example

In the old days, Java developers like to use the StringTokenizer class to split a string. This is because the StringTokenizer class is available since JDK 1.0 and the String.split() is available since JDK 1.4

TestSplit.java

package com.mkyong.test

import java.util.StringTokenizer;

public class TestSplit {

    public static void main(String[] args) {

        String test = "abc.def.123";

        StringTokenizer token = new StringTokenizer(test, ".");

        while (token.hasMoreTokens()) {
            System.out.println(token.nextToken());
        }

    }

}

Output

abc
def
123

Note
This StringTokenizer is a legacy class, retained for compatibility reasons, the use is discouraged! Please use string.split().

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值