首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java字符串到数组的拆分

Java字符串到数组的拆分
EN

Stack Overflow用户
提问于 2016-04-13 17:49:06
回答 3查看 121关注 0票数 1

我有一个字符串,例如:"My brother, John, is a handsome man."

我想把它拆分成一个数组,这样输出就是:

代码语言:javascript
复制
"My" , "brother", "," , "John", "," , "is", "a", "handsome", "man", "."

有人能帮我吗?我需要在Java上做到这一点。

EN

回答 3

Stack Overflow用户

发布于 2016-04-13 17:57:20

replaceAll()split()的组合应该可以做到这一点。

代码语言:javascript
复制
public static void main(String[] args) {
    String s ="My brother, John, is a handsome man.";
    s = s.replaceAll("(\\w+)([^\\s\\w]+)", "$1 $2");  // replace "word"+"punctuation" with "word" + <space> + "punctuation" 
    String[] arr = s.split("\\s+"); // split based on one or more spaces.
    for (String str : arr)
        System.out.println(str);
}

O/P:

代码语言:javascript
复制
My
brother
,
John
,
is
a
handsome
man
.
票数 5
EN

Stack Overflow用户

发布于 2016-04-13 18:01:43

如果只考虑,.,那么一种方法是使用replace()split()

代码语言:javascript
复制
String x =  "My brother, John, is a handsome man.";
String[] s = x.replace(",", " ,").replace(".", " .").split("\\s+"); 

for (String str : s)
    System.out.print("\"" + str + "\"" + " ");

输出:

代码语言:javascript
复制
"My" "brother" "," "John" "," "is" "a" "handsome" "man" "." 
票数 0
EN

Stack Overflow用户

发布于 2016-04-13 18:15:37

尝尝这个。

代码语言:javascript
复制
    String string = "My brother, John, is a handsome man.";
    for (String s : string.split("\\s+|(?=[.,])"))
        System.out.println(s);

结果是

代码语言:javascript
复制
My
brother
,
John
,
is
a
handsome
man
.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36594656

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档