0

So I created a method that takes in a 2D char array that was originally from a text file and would end up outputting a string array. The only problem is the string.split() method doesn't take into account new lines or empty lines and I need the string.length() to be accurate to obtain a word count. Is there code that I am missing? This is the code I have so far.

    public static String[] textString(char[][] text) {
    String string = "";
    for (int i = 0; i < text.length; i++) {
        for (int k = 0; k < text[i].length; k++) {
            string += text[i][k];
        }
        string += "\n";
    }
    String[] stringA = string.split(" ");
    return stringA;
}
dbaltor
  • 2,737
  • 3
  • 24
  • 36
Edge123
  • 7
  • 4
  • A few things to consider, never use `+=` to concatenate `String`(s) in a loop. It is terribly inefficient. Java `String` is immutable. Use a `StringBuilder`. Second, `String.split` takes a regular expression. `return string.split("\\s+");` – Elliott Frisch Apr 21 '20 at 00:26
  • @ElliottFrisch I appreciate you pointing out the inefficiency and also it works now so thank you. – Edge123 Apr 21 '20 at 01:32
  • So boiling it all down, is the *actual* task to calculate how many words are in a `char[][]`? – Bohemian Apr 22 '20 at 05:52
  • @Bohemian that is part of the actual task, yes, but I already finished the code. I'm open to suggestions though since I do want to get better at coding – Edge123 Apr 23 '20 at 17:14

1 Answers1

1

You don't need to create a single String and then split it right after. You can create an array of Strings from the outset using the String(char[]) constructor.

public static String[] textString(char[][] text) { 
  int size = text.length; 
  String[] strings = new String[size]; 
  for (int i = 0; i < size; i++) { 
    strings[i] = new String(text[i]); 
  } 
  return strings; 
}
dbaltor
  • 2,737
  • 3
  • 24
  • 36