Splitting a String of Characters with split() - Example 1
Snippet: Splitting a String of Characters with split()
Explanation
This snippet introduces the split() method, which breaks a String into an array of substrings using a delimiter. Here, a single space " " is used as the delimiter, so each word becomes one element of the resulting String[] array.
The famous pangram "the quick brown fox jumps over the lazy dog" contains 9 words, so words.length is 9. The first word is accessed with words[0] and the last with words[words.length - 1] — a common pattern for accessing the last element of any array.
What You Can Do
Try splitting the string with a different delimiter, like "o". How many parts do you get, and what does each part look like? Are they still words?
You can also try printing all the words in the array one by one. Can you use words.length to know how many times to repeat the print?
Run it and observe the output!
Example List
Additional Resources
- Learn: Declaring Strings
- Learn: Constructing a String
- Learn: Introduction to String Indexing
- Learn: Comparing Two String Objects Using compareTo Methods
- Learn: Comparing String Objects with equals Methods
- Learn: Obtaining Substrings from a String Object
- Learn: Using the split method on a String
- Practice: Evaluating Expressions that use the String Class
- Practice: Writing Code Using the String Class
- FRQ Practice: AP Computer Science A FRQ 1 Formatting Words
- FRQ Practice: AP Computer Science A FRQ 1 Sentence Analysis