Reputation: 123
I am trying to read a line from a file using BufferedReader and Scanner. I can create both of those no problem. What I am looking to do is read one line, count the number of commas in that line, and then go back and grab each individual item. So if the file looked like this:
item1,item2,item3,etc.
item4,item5,item6,etc.
The program would return that there are four commas, and then go back and get one item at a time. It would repeat for the next line. Returning the number of commas is crucial for my program, otherwise, I would just use the Scanner.useDelimiter() method. I also don't know how to return to the beginning of the line to grab each item.
Upvotes: 1
Views: 122
Reputation: 51
If you absolutely must know the number of commas, a similar question has already been answered:
Java: How do I count the number of occurrences of a char in a String?
Upvotes: 0
Reputation: 94499
Why not just split the String
. The split
method accepts a delimiter (regex) as an argument and breaks the String
into a String[]
. This will eliminate the need to return to the beginning
.
String value = "item1,item2,item3";
String[] tokens = value.split(",");
To get the number of commas, just use, tokens.length - 1
Upvotes: 5
Reputation: 205
Split() can be used to achieve this eg:
String Line = "item1,item2,item3"
String[] words =Line.split(",");
Upvotes: 0