0

How does one convert something like this (assuming I'm using a Buffered Reader to read in the info?):

0, blah, hi\n
1, bluh, test

To this:

String[] testArray:
0, blah, hi, 1, bluh, test

If that makes any sense? Basically removing the commas and newlines and inserting each different word into its own element.

TT.
  • 15,774
  • 6
  • 47
  • 88
Burnie
  • 85
  • 3
  • 1
    Why the 1 after the 0? – Maurice Perry Dec 08 '16 at 10:06
  • @MauricePerry Oops, typo. – Burnie Dec 08 '16 at 10:07
  • 2
    What did you try so far? A basic way would be to read everything into a single string and then split by newlines and commas (hint: the `String` class has methods for this). – Thomas Dec 08 '16 at 10:08
  • Yes , it is possible... but you have to define the merging order. .in the example you post makes not much sense – ΦXocę 웃 Пepeúpa ツ Dec 08 '16 at 10:08
  • 1
    Just read each line, split on the coma and concat each resulting array (using a list will be simpler). I let you write the code – AxelH Dec 08 '16 at 10:11
  • 1
    Did you even search online? http://stackoverflow.com/questions/22350683/how-to-split-a-comma-delimited-string-into-an-array-of-empty-strings http://stackoverflow.com/questions/7488643/how-to-convert-comma-separated-string-to-arraylist http://stackoverflow.com/questions/10631715/how-to-split-a-comma-separated-string – denvercoder9 Dec 08 '16 at 10:13

3 Answers3

0

A naive implementation:

List<String> tokens = new ArrayList<>();
for (String line = in.readLine(); line != null; line = in.readLine()) {
    for (String token: line.split(",\\s*")) {
        tokens.add(token);
    }
}
String[] testArray = tokens.toArray(new String[tokens.size()]);
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
0

It's much easier to do such things with a Scanner with a custom delimiter than reinventing the wheel, IMHO:

String str = "0, blah, hi\n1, bluh, test";
Reader reader = new StringReader(str); // Just an example, any Reader would work
Scanner scanner = new Scanner(reader).useDelimiter(", ");
List<String> tmpList = new LinkedList<>();
scanner.forEachRemaining(tmpList::add);
String[] array = tmpList.toArray(new String[tmpList.size()]);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Here's an answer for Java 8.

String[] array = Files.newBufferedReader(PATH_OF_THE_FILE)
    .lines()
    .flatMap(string -> java.util.stream.Stream.of(string.split(",\\s")))
    .collect(Collectors.toList())
    .toArray(new String[0]);
choasia
  • 10,404
  • 6
  • 40
  • 61