1

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.

comscis
  • 123
  • 1
  • 2
  • 8
  • A couple of the answers below give `str.length` for the number of commas. Technically the actual number of commas would be `str.length-1` since there are `str.length` items (with commas in between each). Just wanted to make sure that was mentioned. – thesquaregroot Dec 06 '13 at 21:58
  • @thesquaregroot Good point, I forgot he was counting commas not tokens. – Kevin Bowersox Dec 06 '13 at 21:59
  • Reading your question again though, you say there are 4 commas in your examples, but there are actually only 3 (there are 4 items). So maybe `str.length` is right if you did actually want the number of items. – thesquaregroot Dec 06 '13 at 22:02
  • @thesquaregroot great point. Technically I asked about the num of commas, but the actual length will do for my purposes. Good eye though. – comscis Dec 06 '13 at 22:02

3 Answers3

5

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

String.split() Documentation

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
0

Split() can be used to achieve this eg:

String Line = "item1,item2,item3"
String[] words =Line.split(",");
0

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?

Community
  • 1
  • 1
Mathias
  • 51
  • 3