In: Computer Science
Write a static method startsWith that inputs two Strings and returns a boolean. If the first input starts with the substring that is the second input, then the method returns true; otherwise, it returns false.
For example,
|
startsWith( "radar installation", "rad" ) |
returns |
true |
|
startsWith( "radar installation", "installation" ) |
returns |
false |
|
startsWith( "radar installation", "" ) |
returns |
true |
|
startsWith( "", "a" ) |
returns |
false |
|
startsWith( "", "" ) |
returns |
true |

public static boolean startsWith(String s1, String s2) {
if (s2.length() <= s1.length()) {
for (int i = 0; i < s2.length(); i++) {
if (s1.charAt(i) != s2.charAt(i)) {
return false;
}
}
return true;
}
return false;
}

public class StartsWith {
public static boolean startsWith(String s1, String s2) {
if (s2.length() <= s1.length()) {
for (int i = 0; i < s2.length(); i++) {
if (s1.charAt(i) != s2.charAt(i)) {
return false;
}
}
return true;
}
return false;
}
public static void main(String[] args) {
System.out.println(startsWith("radar installation", "rad"));
System.out.println(startsWith("radar installation", "installation"));
System.out.println(startsWith("radar installation", ""));
System.out.println(startsWith("", "a"));
System.out.println(startsWith("", ""));
}
}
