Introduction to String Indexing
String Indexing
Each character of a String literal has an associated index, or label, with the first character being index 0 and each subsequent index is one more than the last. Consider the following example.
- The index of
Dis 0. - The index of
uis 1. - The index of
kis 2. - The index of
eis 3.
int length()
This method returns the number of characters that are in the String.
Your Turn
Let's try it in the Java Playground.
- Predict the value of
wordLength. - Add a statement to compute the length of
phraseand assign it towordLength. - Predict the new value of
wordLength. - Run the code to check you predictions.
- wordLength is assigned the value 4, since there are 4 characters in
Duke. - phraseLength is assigned the value 15, since there are 13 letters and two spaces in
phrase.
char charAt(int index)
This method returns the char value at the specified index.
Your Turn
Let's try it in the Java Playground.
- add a statement to use
charAtto access the last character ofphraseand assign it to a variable namedlast.
startis assignedDsince that is the character at index 0.middleis assignedvsince that is the 8th character in phrase or the character at index 7.
int indexOf(String str)
This method returns
- the index within this string of the first occurrence of the parameter
str. - -1 if this word does not contain an occurrence of
str.
Your Turn
Let's try it in the Java Playground.
- Predict the values of
index1,index2, andindex3. - Run the code to see if your predictions are correct.
index1is assigned the value7. Starting withAbeing at index0, theninnessis at index7.index2is assigned the value3. Starting withAbeing at index0, thesinsomeis at index3.index3is assigned teh value-1. This method distinguishes between upper and lowercase letters, soAwesomeandawesomeare considered different values. As such,awesomedoes not appear inword.
There are multiple indexOf methods that take different parameters, some specifying the range of indexes where str is being searched.
Complete List of String Learn Tutorials
- Learn: Declaring Strings
- Learn: Constructing a String
- Learn: String Indexing
- Learn: Comparing Strings with compareTo methods
- Learn: Comparing Strings with equals methods
- Learn: Creating Substrings
- Learn: Creaing a new String with the Case Changed
Resources
- Learn: Declaring Strings
- Learn: Introduction to Arithmetic Expressions
- Learn: Introduction to Console Input and Output
- Learn: Formatting Output with Escape Sequences and Text Blocks
- Practice: Evaluating Expressions that Use String Methods
- Practice: Write Code that Uses the String Methods
- Practice: AP Computer Science A String Free Response Questions