- #1
Arnoldjavs3
- 191
- 3
Homework Statement
Given a string and a non-empty word string, return a string made of each char just before and just after every appearance of the word in the string. Ignore cases where there is no char before or after the word, and a char may be included twice if it is between two words.
Homework Equations
The Attempt at a Solution
Java:
public String wordEnds(String str, String word) {
String newString = "";
for(int i=0; i<str.length()-word.length(); i++) {
int finalCheck = str.length()-word.length();
if(str.substring(i, i+word.length()).equals(word)) {
if(i!=0) {
newString += "" + str.charAt(i-1);
}
newString += "" + str.charAt(i+word.length());
}
}
return newString;
}
wordEnds("abc1abc1abc", "abc") → "1111" got "111") It isn't adding the last char before the last index.)
So I made this code which works but it's not incorporated for inside the loop which I'd like to do
Java:
public String wordEnds(String str, String word) {
String newString = "";
for(int i=0; i<str.length()-word.length(); i++) {
int finalCheck = str.length()-word.length();
if(str.substring(i, i+word.length()).equals(word)) {
if(i!=0) {
newString += "" + str.charAt(i-1);
}
newString += "" + str.charAt(i+word.length());
}
}
int finalOccurence = str.length()-word.length();
if(str.length()>word.length()&&str.substring(finalOccurence).equals(word)) {
newString+="" + str.charAt(finalOccurence-1);
}
return newString;
}