0

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))
JJJ
  • 32,902
  • 20
  • 89
  • 102
cscontrol
  • 73
  • 7
  • What language are you using? – Gonzalo Lorieto Jul 30 '18 at 17:57
  • one trick is before matching change both string to either upper or lower case and this will act like case-insensitive check – Laxmikant Jul 30 '18 at 18:02
  • I'm using java. – cscontrol Jul 30 '18 at 18:18
  • if i change the user input to all lowercase "emily" or all uppercase "EMILY", how will it find "Emily"? – cscontrol Jul 30 '18 at 18:20
  • Possible duplicate of [How to check if a String contains another String in a case insensitive manner in Java?](https://stackoverflow.com/questions/86780/how-to-check-if-a-string-contains-another-string-in-a-case-insensitive-manner-in) – Silvio Mayolo Jul 30 '18 at 18:43
  • When you ask a question, please remember to add the language (Java) as a tag. Also review [how to format code](https://stackoverflow.com/editing-help#code). – JJJ Jul 30 '18 at 18:45

1 Answers1

1

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);
Sunny Patel
  • 7,830
  • 2
  • 31
  • 46