1

I am newbie for java language. I am want to split the string "mandar\jitendra\sadye" to 3 strings "mandar","jitendra" and "sadye" using split function in string library. The program that I use to split the string is as follow:

public class string 
{
    public static void main(String[] args) 
    {
        String mandar="mandar\\jitendra\\saye";
        String[] words=mandar.split("[\\]");
        for(int a=0;a<words.length;a++)
        {
            System.out.println(words[a]);
        }
    }
}

But this program gives this errorimage of error from command prompt If i replace '\' by any other escape sequence like'\0' then program runs just fineoutput when '\' is replaced by '\0' I already tried using ['\'] [] [\] ['\'] [\] but none of these tokens are working for me. So is there a some special way for for splitting a string across '\'?

0

1 Answer 1

5

You need to escape the \ correctly. Once for java, again for regex engine.

    String mandar="mandar\\jitendra\\saye";
    String[] words=mandar.split("\\\\");
    for(int a=0;a<words.length;a++)
    {
        System.out.println(words[a]);
    }

O/P :

mandar
jitendra
saye

Another approach I would think about is using Pattern.quote():

public static void main(String[] args) {
    String mandar="mandar\\jitendra\\saye";
    String[] words=mandar.split(Pattern.quote("\\"));
    for(int a=0;a<words.length;a++)
    {
        System.out.println(words[a]);
    }
}

O/P :

mandar
jitendra
saye
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.