Getting a Substring from a String, a Begin Index and an End Index - Example 3
Snippet: Getting a Substring from a String, a Begin Index and an End Index
Explanation
This snippet continues with the two-argument form of substring(), this time extracting a word from the middle of the string. Calling message.substring(6, 11) extracts characters from index 6 (inclusive) to index 11 (exclusive), giving "World" — without the trailing "!".
The character at index 11 is '!', and since the end index is exclusive, it is not included in the result. This shows how precise you can be with substring() — you can extract exactly the characters you want.
What You Can Do
Try extracting just the "!" at the end. Which indexes would you use? You can check your answer with both the one-argument and two-argument forms of substring().
You can also try combining the two substrings from this snippet and the previous one — hello + " " + world — and compare it to message.substring(0, 11). Are they equal?
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