3 min readβ’december 23, 2022
Milo Chang
Peter Cao
Milo Chang
Peter Cao
public static String reverse(String s) {
String result = ""
for (int i = 0; i < string.length(); i++) {
result = s.substring(i,i+1) + result;
}
return result;
}
n
to 1. To get longer substrings, we increase n
to the length of the substrings you want to find. This value can be up to the length of the overall string itself, but no more. This would create an exception. n
. the length of the string + 1 - n
.public static void printSubstringsLengthN(String s, int n) {
for (int i = 0; i < (s.length() + 1 - n); i++) {
System.out.println(s.substring(i, i+n));
}
}
checkForSubstring("house", "us");
would return true while checkForSubstring("bob", "us");
would return false. public static boolean checkForSubstring(String s, String n) {
for (int i = 0; i < (s.length() + 1 - n.length()); i++) {
String currentSubString = (s.substring(i, i+n.length()));
if (currentSubString.equals(n)) {
return true;
}
}
return false;
}
countSubstrings("banana", "a");
will return the number of times the letter "a" is in the word "banana," which is 3 in this case. We can also call countSubstrings("ABBBAABBAABBABAB", "ABBA");
which will return the number of times "ABBA" is in the input String, which in this case is 2.public static int countSubstrings(String s, String n) {
int count = 0;
for (int i = 0; i < (s.length() + 1 - n.length()); i++) {
String currentSubString = (s.substring(i, i+n.length()));
if (currentSubString.equals(n)) {
count++;
}
}
return count;
}
Β© 2023 Fiveable Inc. All rights reserved.