java,split 如何设置多个分隔符?

如题所述

java中String类的split方法接受正则表达式作为参数,我们可以使用正则表达式实现多个分隔符进行分隔的效果。
示例代码如下:

import java.util.*;
import java.lang.*;
import java.io.*;
 
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String str = "abc;123,456?999|haha";
        String[] strs = str.split("[;,?|]");
        for(String s : strs){
            System.out.println(s);
        }
    }
}

执行结果:
abc
123
456
999
haha

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-05

实用|连接多个分隔符。

例如用;和空格分割:

 String[]vertices = a[i].split(";| ");

其他经验:

1、分隔符为“.”(无输出),“|”(不能得到正确结果)转义字符时,“*”,“+”时出错抛出异常,都必须在前面加必须得加"\\",如split(\\|);
2、如果用"\"作为分隔,就得写成这样:String.split("\\\\"),因为在Java中是用"\\"来表示"\"的,字符串得写成这样:String Str="a\\b\\c";

追问

谢谢

追答

不客气

本回答被提问者采纳
第2个回答  2018-01-06
为什么我手机看不到完整答案
相似回答