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;
}
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+"); Commented Apr 21, 2020 at 0:26
  • @ElliottFrisch I appreciate you pointing out the inefficiency and also it works now so thank you. Commented Apr 21, 2020 at 1:32
  • So boiling it all down, is the actual task to calculate how many words are in a char[][]? Commented Apr 22, 2020 at 5: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 Commented Apr 23, 2020 at 17:14

1 Answer 1

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; 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.