0

For some reason this parsing technique doesn't work when I use "|" to parse the string. My java code looks like this

public class Testing{
    public static void main(String[] args){
        String sentence = "SA|2|What is the capital of Italy|Rome";
        System.out.println(sentence);
        System.out.println("---------------------------");

        String[] tokens = sentence.split("|");
        for(String word: tokens)
            System.out.println(word);
    }
}

So my output looks like this for some reason

SA|2|What is the capital of Italy|Rome
---------------------------
S
A
|
2
|
W
h
a
t

i
s

t
h
e

c
a
p
i
t
a
l
...(and so on)

What I want it to do is to display the entire string like this instead of what it is giving me like this

SA|2|What is the capital of Italy|Rome
---------------------------
SA
2
What is the capital of Italy
Rome

Does anybody know why it is causing every letter to be printed per line and doesn't print it with every word?

Enigo
  • 3,685
  • 5
  • 29
  • 54
Programmer
  • 105
  • 2
  • 11

4 Answers4

0

To reference the following answer on SO

Splitting a Java String by the pipe symbol using split("|")

you need to say sentence.split("\\|"); the reason for this is that |, as i mentioned in the comment, is a symbol for OR. Thus, say you wanted to split something on a dot or a white space you would say sentence.split("\.| ")

Community
  • 1
  • 1
SomeStudent
  • 2,856
  • 1
  • 22
  • 36
  • Hint: when you already know that it is a duplicate; why didn't you close vote as such? – GhostCat Mar 01 '17 at 05:53
  • Hmm, good point, truth be told not sure how to do it. Just figured i may as well quickly answer it both in comments and as a answer for the benefit of the OP> – SomeStudent Mar 01 '17 at 05:54
0
public static void main(String []args){
    String sentence = "SA|2|What is the capital of Italy|Rome";
    System.out.println(sentence);
    System.out.println("---------------------------");

    String[] tokens = sentence.split("\\|");
    for(String word: tokens){
        System.out.println(word);
    }
 }

Use above code. as for special characters escape syntax is required. so use \\ before your special character.

santosh gore
  • 319
  • 2
  • 21
0

Change the split to

final String[] tokens = sentence.split("\\|");
MSD
  • 1,409
  • 12
  • 25
0
String[] tokens = sentence.split("\\|");

This is work for you.

Harshad Chhaiya
  • 125
  • 2
  • 11