gpt4 book ai didi

java - 分割字符串法

转载 作者:行者123 更新时间:2023-12-02 00:05:06 25 4
gpt4 key购买 nike

我已经用java编写了一段代码,如下所示

public class sstring  
{
public static void main(String[] args)
{
String s="a=(b+c); string st='hello adeel';";
String[] ss=s.split("\\b");
for(int i=0;i<ss.length;i++)
System.out.println(ss[i]);
}
}

这段代码的输出是

a
=(
b
+
c
);
string

st
='
hello

adeel
';

我应该怎么做才能拆分 =( 或 );等在两个单独的元素而不是单个元素中。在这个数组中。即我的输出可能看起来像

a
=
(
b
+
c
)
;
string

st
=
'
hello

adeel
'
;

这可能吗?

最佳答案

这与每个查找的单词 \\w+(小写 w)或非单词字符 \\W(大写 W)匹配。

这是一个不被接受的答案 can split string method of java return the array with the delimiters as well @RohitJain 的上述评论。

public String[] getParts(String s) {
List<String> parts = new ArrayList<String>();
Pattern pattern = Pattern.compile("(\\w+|\\W)");
Matcher m = pattern.matcher(s);
while (m.find()) {
parts.add(m.group());
}
return parts.toArray(new String[parts.size()]);
}

关于java - 分割字符串法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14043395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com