用词分隔java中的字符串 [英] Split Strings in java by words

查看:78
本文介绍了用词分隔java中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将以下单词拆分为数组

How can I split the following word in to an array

这就是代码

进入

array
0 That
1 s
2 the
3 code

我尝试过这样的事情

String str = "That's the code";

        String[] strs = str.split("\\'");
        for (String sstr : strs) {
            System.out.println(sstr);
        }

但输出是

That
s the code


推荐答案

要专门拆分空格和撇号:

To specifically split on white space and the apostrophe:

public class Split {
    public static void main(String[] args) {
        String [] tokens = "That's the code".split("[\\s']");
        for(String s:tokens){
            System.out.println(s);
        }
    }
}

或拆分任何非单词字符:

or to split on any non word character:

public class Split {
    public static void main(String[] args) {
        String [] tokens = "That's the code".split("[\\W]");
        for(String s:tokens){
            System.out.println(s);
        }
    }
}

这篇关于用词分隔java中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆