cscontrol
cscontrol

Reputation: 73

Search for String case-insensitive

I want to search for any name in a text file. For example, the name is written as Emily in the text file.

If the user types "emily" or "EmiLY" the code should find the name Emily.

I need this code below to be case-insensitive. Right now it searches for Emily but not emily

(search.startsWith(name) && search.endsWith(name))

Upvotes: 0

Views: 53

Answers (1)

Sunny Patel
Sunny Patel

Reputation: 8077

If you really need to use the code you posted, you just push both items to lowercase and then do the comparison.

string searchLower = search.toLowerCase();
string nameLower = name.toLowerCase();
boolean isIncluded = searchLower.startsWith(nameLower) && searchLower.endsWith(nameLower);

Otherwise, if you're actually trying to find if name is contained in your search. Then you can use org.apache.commons.lang3.StringUtils from the Apache Commons library.

boolean isIncluded = StringUtils.containsIgnoreCase(search, name);

Upvotes: 1

Related Questions