Introduction: 4.3.0

  • Loops can be used for string traversals or string processing
    • The code steps through a string character-by-character
  • The first character in a string is at index 0
    • The last is at length()-1
0 1 2 3
d u c k

Strings are a sequence of characters where each character is at an index

String methods

  • int length()
    • returns the number of characters in a String object.
  • int indexOf(String str)
    • returns the index of the first occurrence of str
      • returns -1 if not found.
  • String substring(int from, int to)
    • returns the substring beginning at index from and ending at index (to – 1)
    • Note that s.substring(i,i+1) returns the character at index i.
  • String substring(int from)
    • returns substring(from, length()).

While find and replace loop: 4.3.1

  • A while loop can be used with String.indexOf to find certain character in a string and process them
String message = "P1ease have a 1ong and happy 1ife";
int counter = 0;

// While the replacement keywords exist
while (message.indexOf("1") >= 0) {
    // find the index of the next thing to replace
    int index = message.indexOf("1");
    message = message.substring(0, index) + "l" + message.substring(index+1);
    counter++;
}

Reverse String: 4.3.2

  • for loops can be used where you know you’ll visit every character
    • while loops are good when you don’t know how many iterations you’ll have
    • start at 0
    • use the string’s length() for the ending condition
String s = "I like programming, programming is fun";

// loop through from 0 to length of string
for (int i=0; i < s.length(); i++) {
    String nthLetter = s.substring(i, i+1);
    System.out.println(nthLetter);
}

String newMessage = "";
// print the string backwards!
for (int i=s.length(); i >= 0; i--) {
    System.out.print(s.substring(i-1, i));
    newMessage += s.substring(i-1, i);
}

Summary: 4.3.4

  • loops can be used to traverse and process strings
  • There are standard algorithms to:
    • Find if one or more substrings have a particular property
    • Determine if the number of substrings which meet a certain criteria
    • Create a new string with the characters reversed