Skip to main content
Engineering LibreTexts

17.3: String Traversal

  • Page ID
    15265
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    The following loop traverses the characters in fruit and displays them, one on each line:

    for (int i = 0; i < fruit.length(); i++) {
        char letter = fruit.charAt(i);
        System.out.println(letter);
    }
    

    Strings provide a method called length that returns the number of characters in the string. Because it is a method, you have to invoke it with the empty argument list, ().

    The condition is i < fruit.length(), which means that when i is equal to the length of the string, the condition is false and the loop terminates.

    Unfortunately, the enhanced for loop does not work with strings. But you can convert any string to a character array and iterate that:

    for (char letter : fruit.toCharArray()) {
        System.out.println(letter);
    }
    

    To find the last letter of a string, you might be tempted to try something like:

    int length = fruit.length();
    char last = fruit.charAt(length);      // wrong!
    

    This code compiles and runs, but invoking the charAt method throws a StringIndexOutOfBoundsException. The problem is that there is no sixth letter in "banana". Since we started counting at 0, the 6 letters are indexed from 0 to 5. To get the last character, you have to subtract 1 from length.

    int length = fruit.length();
    char last = fruit.charAt(length - 1);  // correct
    

    Many string traversals involve reading one string and creating another. For example, to reverse a string, we simply add one character at a time:

    public static String reverse(String s) {
        String r = "";
        for (int i = s.length() - 1; i >= 0; i--) {
            r = r + s.charAt(i);
        }
        return r;
    }
    

    The initial value of r is "", which is the empty string. The loop traverses the letters of s in reverse order. Each time through the loop, it creates a new string and assigns it to r. When the loop exits, r contains the letters from s in reverse order. So the result of reverse("banana") is "ananab".


    This page titled 17.3: String Traversal is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) .

    • Was this article helpful?