4.3 String Iteration

Methods of iterating through and interacting with strings

String word = "sunflower";
String sub = "low";
boolean found = false;
for (int i = 0; i < word.length()-sub.length(); i++) {
    String portion = word.substring(i, i+sub.length());
    if (portion.equals(sub)) {
        found = true;
    }
}
System.out.println(found);
true

What is a substring?

  • a substring is a subset of the main string
  • the substring(a,b) method creates a substring with the characters of the original string with indices of a to b.
  • string.length() returns the length of the string
  • string1.equals(string2) determines if the two strings have the same characters

Fun Stubstring Hack:

Create a program that scrables any word that you put in, by reversing the first and last letters, then reversing the center letters. (example: sold becomes dlos, computer becomes retupmoc)

String word = "computer";
String scrambled = "";
for (int i = word.length()-1; i >= 0; i--) {
    scrambled += word.charAt(i);
}
System.out.println(scrambled);
retupmoc