Skip Top Navigation Bar

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 D is 0.
  • The index of u is 1.
  • The index of k is 2.
  • The index of e is 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 phrase and assign it to wordLength.
  • 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 charAt to access the last character of phrase and assign it to a variable named last.

  • start is assigned D since that is the character at index 0.
  • middle is assigned v since 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, and index3.
  • Run the code to see if your predictions are correct.

  • index1 is assigned the value 7. Starting with A being at index 0, the n in ness is at index 7.
  • index2 is assigned the value 3. Starting with A being at index 0, the s in some is at index 3.
  • index3 is assigned teh value -1. This method distinguishes between upper and lowercase letters, so Awesome and awesome are considered different values. As such, awesome does not appear in word.

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

Resources

Next Learn Tutorial