简体   繁体   English

分割字符串方法

[英]split string method

i have written a code in java as given under 我已经按照下面的代码用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]);  
    }  
}   

and the output of this code is 这个代码的输出是

a
=(
b
+
c
);
string

st
='
hello

adeel
';

what should i do in order to split =( or ); 我应该怎么做才能拆分=(或); etc in two separate elements rather than single elements. 等等,分为两个单独的元素,而不是单个元素。 in this array. 在这个数组中。 ie my output may look as 即我的输出可能看起来像

a
=
(
b
+
c
)
;
string

st
=
'
hello

adeel
'
;

is it possible ? 可能吗 ?

This matches with every find either a word \\\\w+ (small w) or a non-word character \\\\W (capital W). 这与每个找到的单词都匹配\\\\w+ (小w)或非单词字符\\\\W (大写W)。

It is an unaccepted answer of can split string method of java return the array with the delimiters as well of the above comment of @RohitJain. java可拆分字符串方法返回带有分隔符的数组以及 @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()]);
}

Use this code there.. 在此使用此代码。

Pattern pattern = Pattern.compile("(\\w+|\\W)");
Matcher m = pattern.matcher("a=(b+c); string st='hello adeel';");
while (m.find()) {
System.out.println(m.group());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM