CS173: Intro to Computer Science - Strings (3 Points)
Developed by Professor Tralie and Professor Mongan.Exercise Goals
The goals of this exercise are:- To iterate over
String
variables.
String
s are equal, by checking them character by character. Loop over all characters up to the length of the string, and obtain each character using the str1.charAt(i)
or the str1.substring(i, i+1)
method (and str2.charAt(i)
or the str2.substring(i, i+1)
, for the other string, as well).
Enter your Ursinus netid before clicking run. This is not your ID number or your email. For example, my netid is wmongan
(non Ursinus students can simply enter their name to get this to run, but they won't get an e-mail record or any form of credit).
Netid |
CompareStrings.java
public class CompareStrings {
/*
* Compare the strings str1 and str2, character by character,
* and return true if they are equal and the same size.
* @param str1 The first string to compare
* @param str2 The second string to compare
* @return true if the strings are equal, false if not
*/
public static boolean compare(String str1, String str2) {
// TODO: If str1.length() is not equal to str2.length(), return false
// TODO: Loop over each character and check that str1.charAt(i) equals str2.charAt(i).
// ... If not, return false
// ... Hint: stop your loop at the smaller of the two string lengths (use Math.min() for this)!
return true;
}
}
Driver.java
public class Driver {
public static void checkEqual(String x, String y) {
boolean isEqual = CompareStrings.compare(x, y);
System.out.println(isEqual);
}
public static void main(String[] args) {
String x = "bat";
String y = "bat";
checkEqual(x, y);
String a = "testing";
String b = "debugging";
checkEqual(a, b);
String c = "bat";
String d = "cat";
checkEqual(c, d);
String s = "computer";
String t = "science";
checkEqual(s, t);
String s = "bat";
String t = "bar";
checkEqual(u, v);
}
}
Driver.main(null);