Implementing String Algorithms
- Developing Algorithms Using Strings
- Finding a substring within a string
- I T E R A T E
- POPCORN HACK: Run the code.. what happened? How can we fix it?
- Another issue:
- I T E R A T E
- HACKS
Developing Algorithms Using Strings
LEARNING OBJECTIVES:
For algorithms in the context of a particular specification that involves String
objects:
- identify standard algorithms
- modify standard algorithms
- develop an algorithm
Java has many methods that are helpful when working with strings:
String .substring
–> retrieves portion of a stringString .equals
–> compares two stringsString .length
–> returns length of a stringfor Loop
–> iterating through characters of a string
Finding a substring within a string
We can use the “window” method:
A “window” is created the same length as the substring. We then iterate through the main string in sections and compare to the substring
For example:
I T E R A T E
with substring “ERA”
public class StringFinder {
public static void main(String[] args) {
String word = "iterate";
String sub = "xxx";
boolean found = false; // will be set to true once substring is found
for (int i = 0; i < word.length(); i++) { //iterating forwards: starting at first index (0) and going to the length of the word.. let's try word.length
String portion = word.substring(i, i + sub.length());
if (sub.length() > portion.length()) break;
if (portion.equals(sub)) { // make sure you use .equals!!
found = true;
break;
}
}
if (found)
System.out.println("substring is found within string!");
else
System.out.println("substring is NOT within string");
}
}
StringFinder.main(null);
POPCORN HACK: Run the code.. what happened? How can we fix it?
Tell us below!
Another issue:
I T E R A T E
What if our substring was the word “RATE”? Note that RATE is at the end of the whole string
HACKS
Create a algorithm similar to the one above. Except this time, use iteration to count the number of vowels within the main string.
HINT: Use the boolean expressions we have learned in previous lessons. Which would you use when comparing your “window” with multiple options of substrings?