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

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

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