Question

I would like to ask you for your help, regarding this code. I am trying to do a kind of encoding of particular words, such as "Microsoft" etc. (random ones, just to learn the technique). I've suceeded in doing everything, but to make this kinf of searching for words case insesitive. Here is the code:

public class BannedWords {

public static String returnStars(int length){
    String stars = "";
    String addStar = "*";
    for (int i = 1; i<=length; i++){
        stars += addStar;
    }
    return stars;
}
public static void main(String[] args) {
    String textString = "Microsoft announced its next generation Java compiler today."
            + " It uses advanced parser and special optimizer for the Microsoft JVM.";
    StringBuilder text = new StringBuilder(textString);
    String bannedWords = "Java, JVM, Microsoft";

    String [] bWordsArr = bannedWords.split("[, ]+");

    for(int i = 0; i<bWordsArr.length; i++){
        int index = textString.indexOf(bWordsArr[i]);
        while(index != -1){
        text = text.replace(index, index+bWordsArr[i].length(), returnStars(bWordsArr[i].length()));
        index = textString.indexOf(bWordsArr[i], index +1);

        }
    }
        System.out.println(text.toString());
    }
}

I need to search for "Java", "JVM" and "Microsoft" words regardless of their case, even if we try "MiCrosoFt" it should work, but after a few hours thinking and trying to do it with using toUpperCase(), toLowerCase(), I couldn't find out how to do that. Do you have any ideas ?

Thank you beforehand ! :)

Was it helpful?

Solution

When using indexOf(), toLowerCase() will convert checked text to lowercase. Then, you must put your search terms in lowercase.

String text = "Java is a good programming language.";
int index = text.toLowerCase().indexOf("java");

You can also use toUpperCase(), simply put your search terms in uppercase.

OTHER TIPS

Actually you should be using equalsIgnoreCase. This is the correct way of comparing strings irrespective of their case. And also you don't have to modify the original string to upper or lower case to perform check. I hope it helps :)

yourString.equalsIgnoreCase(anotherString)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top