Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a String in java at a tab

Tags:

java

string

split

I am attempting to split a String into 2 separate Strings, one from the first letter up until a tab, and the other beginning after the tab and ending at the end of the String. I have looked over this post and have found my problem to be different. I am currently trying to utilize the split() method, but with no luck. My code is as follows:

        Scanner loadFile = new Scanner(System.in);
        loadFile = new Scanner(menuFile);

        //loops through data and adds into the SSST
        while(loadFile.hasNextLine()){
            String line = loadFile.nextLine();

            String[] thisLine = line.split(" ");

            System.out.println(thisLine[0]);
            String item = thisLine[0];
            String value = thisLine[1];

            menu.put(item, value);

I run into my problem at the line line.split(" "); because I do not know the argument to provide to this method in order to split at the tab in my String.

menu in this code is a separate object and is irrelevant.

Sample input for this program:

"baguette          400"

Desired output for this program:

String 1: "baguette" 

String 2: "400"
like image 972
A. Takami Avatar asked Feb 14 '26 23:02

A. Takami


1 Answers

The tab character is written \t. The code for splitting the line thus looks like this:

String[] thisLine = line.split("\t");

More flexible, if feasible for your use case: For splitting on generic white space characters, including space and tab use \\s (note the double reversed slash, because this is a regex).

like image 140
qqilihq Avatar answered Feb 17 '26 20:02

qqilihq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!