0

I have written one java thread to split string

public void run() {

String input="Sasi|maran|rishabh";

String arr[]=input.split("|");
    for (int i = 0; i < arr.length; i++) {
        try{

            System.out.println(arr[i]);

            Thread.sleep(1000);

        }catch(Exception e){
            e.printStackTrace();
        }

    }

}

output expectation:

sasi
rishabh
maran

But what output i am getting :

S
a
s
i
|
m
a
r
a
n
|
r
i
s
h
a
b
h
Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
  • 2
    I suggest you read the documentation for `String.split` *very carefully*, and consider what `|` means in regular expressions... – Jon Skeet Apr 06 '17 at 10:02
  • Both answers below do not seem to deal explain how OP wants "rishabh" to print before "maran" when they are not reordering arr[] at all? – Sash Sinha Apr 06 '17 at 10:04

3 Answers3

0

You need to escape the pipe | like: String[] arr = input.split("\\|"); and do System.out.print(element); instead of System.out.println(arr[i]);

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

String#split method takes regex as an argument. | is a meta character, and it's have a special meaning in regex. Just escape it.

String arr[]=input.split("\\|");
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

use the below code

 input.split("\\|")
Zubair Nabi
  • 1,016
  • 7
  • 28