Mandrek
Mandrek

Reputation: 1211

How to split number using a separator in java

i have an input in a file where i have some numbers in the format

106,648|403,481 747,826|369,456 758,122|365,637 503,576|808,710 325,374|402,513

not i want to format the number as 106,648 403,481 747,826 .. and so on but i am unable to do this i have done this so far

public class MidPointSum {

public static void main(String[] args) {

    File file=new File("D:/midpoint.txt");

    try{

        Scanner sc=new Scanner(file);

            while(sc.hasNext()){

                String value=sc.next();

                String getVal[]=value.split("|");
                for(int i=0;i<getVal.length;i++){

                    System.out.println(getVal[i]);
                }

            }

    }catch(FileNotFoundException e){
        System.err.println("File is not Found");
    }catch (Exception e){
        System.err.println("Another Exception");
    }

}

but i am not getting the desired output.Please someone help me ..

Upvotes: 0

Views: 97

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

| is a regex metacharacter and it needs to be escaped, try "\\|"

Upvotes: 1

Will
Will

Reputation: 14519

Java's split uses a regex, so you need to double escape pipe:

String[] getVal=value.split("\\|");

If it were a plain regex you'd need to escape it anyway, but in java "\" is a special character in a string, due to characters like \t and \n, hence the double escape.

Upvotes: 2

Related Questions