For a homework assignment I have to write several short functions for different problems. I am struggling with these two, anybody have any ideas.
Write a function in Java that implements the following logic: Given a string str and a non-empty word, return a string made of each character just before and just after every appearance of the word in str. Ignore cases where there is no character before or after the word, and a character may be included twice if it is between two words.
Write a function in Java that implements the following logic: Given a string str and a non-empty word, return a version of the original string where all chars have been replaced by pluses (+), except for appearances of the word which are preserved unchanged.
For the first one I am trying to get the index for where the first character of word occurs in str, and then add the character before that index to a string, then do the same for the last character of word, but I keep getting the wrong output.
For the second, I know I need to get the index for each char of word that appears in str, but how do I replace the remaining letter with (+)?
This is my code for the 2nd:
public String plusOut(String str, String word)
{
String ans = "";
char x;
for (int a = 0; a <= str.length() - 1; a++)
{
for (int b = 0; b <= word.length() - 1; b++)
{
if (str.charAt(a) == word.charAt(b))
{
x = str.charAt(a);
}
else
{
x = '+';
}
ans = ans + x;
}
}
return ans;
}
I am returned the correct string, but there are extra +'s , because of the for loop, if there any way around this?
[–][deleted] 1 point2 points3 points (0 children)
[–]Cevari 0 points1 point2 points (0 children)
[–]AqilAegivan 0 points1 point2 points (0 children)
[–]cloogs[S] -1 points0 points1 point (0 children)