public class TestConsole { public static void main(String[] args) { String sampleString = "Apple Banana Carrot"; String[] animals = sampleString.split(" "); int animalIndex = 1; for (String animal : animals) { System.out.println(animalIndex + ". " + animal); animalIndex++; } } }
Noticed that we incorporated a counter in the logic so that it is clear how many tokens were found. The output is shown below.
1. Apple 2. Banana 3. CarrotThe animal array contains three items in this case.
public class TestConsole { public static void main(String[] args) { String sampleString = "Cat Dog Elephant Fox"; String[] animals = sampleString.split("\\s+"); int animalIndex = 1; for (String animal : animals) { System.out.println(animalIndex + ". " + animal); animalIndex++; } } }
Here is the sample output. Notice that the four items were correctly identified.
1. Cat 2. Dog 3. Elephant 4. Fox
Here is a modified example that parses a String that contains tabs and line feeds:
public class TestConsole { public static void main(String[] args) { String sampleString = "Cat Dog \t Elephant \n Fox \r\n Goat"; String[] animals = sampleString.split("\\s+"); int animalIndex = 1; for (String animal : animals) { System.out.println(animalIndex + ". " + animal); animalIndex++; } } }
And the output is still as expected.
1. Cat 2. Dog 3. Elephant 4. Fox 5. Goat
The animal array contains five items in this case.
public class TestConsole { public static void main(String[] args) { String sampleString = "Cat Dog Elephant Fox"; String[] animals = sampleString.split("\\s"); int animalIndex = 1; for (String animal : animals) { System.out.println(animalIndex + ". " + animal); animalIndex++; } } }
Here is a sample output. Notice that each consecutive whitespace will result to an empty String item in the resulting array.
1. Cat 2. 3. Dog 4. 5. 6. 7. Elephant 8. 9. 10. 11. 12. Fox
The animal array contains twelve items in this case, where eigth are empty Strings.