1. String Arrays, split
Array length vs String length
It is easy to confuse array.length, which is a primitive, to string.length(), which is a function. Let's see an example where we sum up the lengths of multiple words:
public class MyProgram { public static void main(String[] args) { String[] words = {"a","cat","in","the","hat"}; //No parenthesis for array length: System.out.println(words.length); //5 System.out.println(words[0]); //a //These extra parenthesis at the end of length are required: System.out.println(words[0].length()); //1 //Let's sum up all the lengths: int sum = 0; for(int i = 0 ; i < words.length; i++) { sum += words[i].length(); } System.out.println("The sum length is: "+sum); //12 } }
Take great care to know what the type of everything is, that way you wont mix up the two lengths.
The string .split function
The split function allows you to convert a String into an array of Strings. It is particularly useful for converting a sentence with multiple words into an array containing each word. This is best illustrated with an example: "
public class MyProgram { public static void main(String[] args) { String x = "necessity is the mother of invention"; String[] words = x.split(" "); //Every string with spaces in between converts into a new String //Now words is the array {"necessity","is","the","mother","of","invention"} System.out.println(words[0]); //prints "necessity" System.out.println(words[1]); //prints "is" System.out.println(words[words.length-1]); //prints "invention" } }
We could use split, for example, to print the number of characters each word has:
public class MyProgram { public static void main(String[] args) { String x = "necessity is the mother of invention"; String[] words = x.split(" "); //Every string with spaces in between converts into a new String for(int i = 0 ; i < words.length; i++) { System.out.println(words[i]+" has "+words[i].length()+" characters"); } //necessity has 9 characters //is has 2 characters //the has 3 characters //mother has 6 characters //of has 2 characters //invention has 9 characters } }