Reputation: 1773
I'm working on a project that takes in a string, and it creates a file with the string name, But I want it to ban certain words. how would I do this?
String fname = scanner(System.in);
//check if it contains explicit words
if (fname.contains("THE BAD WORD HERE")) {
System.out.println(fname + " contains inappropriate words and is not accepted.");
} else {
System.out.println(fname + " is all good");
//create file
createFile(fname);
}
do I have to use a for loop and go through every char? or is there a simpler way? please help.
Upvotes: 0
Views: 1502
Reputation: 3829
Consider using a Set of bad words...
The problem with this is keeping track of every inappropriate word though. A simpler solution would probably be to remove all vowels, as that would not require a massive set of inappropriate words -- what if you accidentally allow a word that is inappropriate in French or some other language for example?
Anyway, here is a HashSet based solution:
Set<String> badWords = new HashSet<String>();
badWords.add("f*ck");
badWords.add("sh*t");
... etc
Of course you'll want to perform case insensitive compare so:
boolean hasBadWord(String filename, Set<String> badWords) {
String filenameLower = filename.toLowerCase();
for(String badWord : badWords) {
if( filenameLower.contains(badWord) ) {
return true;
}
}
return false;
}
more on sets can be found here: java Sets documentation
Upvotes: 1
Reputation: 1720
You would loop through every "Bad word" and look to see if the String contained the word. If so, you set a flag.
For example:
String[] badWords = new String[5];
//set all of you bad words
String fname = scanner(System.in);
//check if it contains explicit words
boolean containsBadWord = false;
for(String badWord : badWords){
if (fname.contains(badWord)) {
containsBadWord = true;
break;
}
}
if(containsBadWord){
System.out.println(fname + " contains inappropriate words and is not accepted.");
}
else {
System.out.println(fname + " is all good");
//create file
createFile(fname);
}
Upvotes: 1