Blure Blure - 1 month ago 8
Java Question

How to replace words from a String if it contains any word from my String array

I want to replace words that matches with any one in my String array,i tried the code below but it's only replacing the first condition, i believe its because of the return statement but i can't figure out another way to do this.

public String wordsToCorrect (String word)
{
word = word.toLowerCase();
StringBuilder sb;
String[] bro =new String[5];
bro [0] = "bros";
bro [1] = "bro";
bro [2] = "bros";
bro [3] = "broda";
bro [4] = "brother";
String[] brother = bro;
String[] si = new String[6];
si [0] = "sis";
si [1] = "sister";
si [2] = "sista";
si [3] = "6sta";
si [4] = "sisy";
si [5] = "sissy";
String[] sister = si;
for ( int i=0;i < brother.length;i ++ )
{
if ( StringUtils.containsIgnoreCase(word, brother [i]) )
{
StrBuilder replace = new StrBuilder();
replace.append(word);
replace.append(" ");
replace.replaceAll(brother [i], "brother");
return replace.toString();
}
}

for ( int i= 0;i < sister.length;i++ )
{
if ( StringUtils.containsIgnoreCase(word, sister [i]) )
{
StrBuilder replace = new StrBuilder();
replace.append(word);
replace.append(" ");
replace.replaceAll(sister [i], "sister");
return replace.toString();

}
}

Answer
public String wordsToCorrect (String word)
{
    StringBuilder sb;
    String[] bro =new String[5];
    bro [0] = "bros";
    bro [1] = "bro";
    bro [2] = "bros";
    bro [3] = "broda";
    bro [4] = "brother";
    String[] brother = bro;
    String[] si = new String[6];
    si [0] = "sis";
    si [1] = "sister";
    si [2] = "sista";
    si [3] = "6sta";
    si [4] = "sisy";
    si [5] = "sissy";

    List<String> broList = Arrays.asList(bro);
    List<String> sisList = Arrays.asList(si);
    String[] words = word.split("\\s");
    for(int i=0; i<words.length; i++){
        String singleWord = words[i];
        if(broList.contains(singleWord.toLowerCase())){
            words[i] = "brother";
        }else if(sisList.contains(singleWord.toLowerCase())){
            words[i] = "sister";
        }
    }
    return String.join(" ", words);
}

EDIT: added explanation

Your problem is no just the loop ending. If you manage to continue with your loop you can sustitute bro in the word "brother" so you get "brotherther". With my code you first split by space, so you get every word isolated and then match it with the ones you are looking for. I use the lists as it's simpler to use contains. Also you are not needing the ignoreCase as you are doing the .toLower() (I prefer it on the contains argument as this doesn't change the upperCases on the original String).

This code works good with any String that uses spaces as separator. If you need to work also with line breaks you should need to modify the split part and manage to maintain the separators maybe with an approach similar to your initial.