0

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 ?

6
  • Yes it is possible. See this answer: - stackoverflow.com/a/14032866/1679863 Commented Dec 26, 2012 at 16:38
  • 2
    Just noticed that the question was asked by you only. Now what didn't you understand in that solution? Commented Dec 26, 2012 at 16:47
  • actually consecutive special characters are not separated. that's why Commented Dec 26, 2012 at 17:17
  • @RohitJain thanks for your support. i think that string tokenizer class would best suit my problem. isn't it ? Commented Dec 26, 2012 at 17:18
  • @adeeliqbal.. Have you tried to modify the split method I gave to suit your situation. Just include all the delimiters you have in that character class. In this case, you have \\W. So, you can use it. StringTokenizer may work, but it is not suggested to use it. Commented Dec 26, 2012 at 17:20

2 Answers 2

2

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()]);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Just to my surprise, even the asker is same. ;)
@RohitJain okay, today enough with SO ;S
@JoopEggen.. Lol ;) Good night :)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.