adeel iqbal
adeel iqbal

Reputation: 494

split string method

i have written a code in java as given under

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. i.e. my output may look as

a
=
(
b
+
c
)
;
string

st
=
'
hello

adeel
'
;

is it possible ?

Upvotes: 0

Views: 164

Answers (2)

ridoy
ridoy

Reputation: 6332

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());
}

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109557

This matches with every find either a word \\w+ (small w) or a non-word character \\W (capital 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.

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()]);
}

Upvotes: 2

Related Questions