Wednesday, January 18, 2017

java - How do I check if a string contains a word without case sensitivity?





I looked at the other questions like this but I couldn't find one that worked. I'm trying to check if the person replied with something meaning "yes", so I'm checking for several words that mean yes. But if they reply with "yEs", my code won't work because its case sensitive, and I don't know what to do.



Code:



String fq = JOptionPane.showInputDialog(null, "Welcome to RadinBot! Would you like to continue?", "RadinBot", JOptionPane.YES_NO_CANCEL_OPTION);


if (fq.contains("yes") ||
fq.contains("Yeah") ||
fq.contains("Yup") ||
fq.contains("mhm") ||
fq.contains("Yea") ||
fq.contains("sure"))

Answer



You can just use toLowerCase() to remove the case sensitivity:




if (fq.toLowerCase().contains("yes") || fq.toLowerCase().contains("yeah") || fq.toLowerCase().contains("yup") || fq.toLowerCase().contains("mhm") || fq.toLowerCase().contains("yea") || fq.toLowerCase().contains("sure"))

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...