Next: None. Up: Strings. Previous: Equality testing.


Example

Say we want a program that finds the longest common prefix of two strings? For example, the longest prefix common to both CAROLING and CAROB is CARO.

We might do this using the following.

import csbsju.cs160.*;

public class Example {
    public static void run() {
        IO.println("Type two strings.");
        String a = IO.readString();
        String b = IO.readString();

        for(int i = 0; ; i++) {
            if(a.charAt(i) != b.charAt(i)) {
                IO.println("Prefix is " + a.substring(0, i));
                break;
            }
        }
    }
}
This program compiles fine. And if I ran it, I would get the following. (User input in boldface.)
Type two strings.
CAROLING CAROB
Prefix is CARO
This is the correct behavior.

And yet the program doesn't always work correctly? What's wrong, and how can you fix it?


Next: None. Up: Strings. Previous: Equality testing.