144

I want to use string.startsWith() method but ignoring the case.

Suppose I have String "Session" and I use startsWith on "sEsSi" then it should return true.

How can I achieve this?

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
Sheetal Bhatewara
  • 1,537
  • 2
  • 9
  • 10
  • 6
    There was no reason to close this question. Anyway, the best solution is to use `string.regionMatches(true, 0, prefix, 0, prefix.length());` which doesn't incur the cost of "normalizing" both strings. – isapir Dec 06 '16 at 19:11
  • @AlexanderAbakumov Fine by me. The correct answer is posted in my comment above. It is much more efficient than changing the case of strings. It'd be good to upgrade it to an answer rather than a comment. – isapir Oct 09 '18 at 21:39

10 Answers10

119

Use toUpperCase() or toLowerCase() to standardise your string before testing it.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
Nemesis
  • 2,750
  • 2
  • 22
  • 20
  • 15
    The big problem here is the performance. For small Strings no problem, but if you have a big one... I mean... Do you really will do a toUpperCase in a 1mb String just to compare 4-10 inicial characters? – Dyorgio Apr 07 '16 at 16:52
  • 7
    Hum even if i can't see why i would like to compare the starting part of a 1mb String then if only 4 - 10 initial characters interest me i use substring and then normalize and done... – Nemesis Apr 09 '16 at 20:31
  • 4
    This answer (and all other answers found herein) are wrong. If you look at the implementation of `String.equalsIgnoreCase()` you will discover that you need to compare **both** lowercase and uppercase versions of the Strings before you can conclusively return `false`. See http://stackoverflow.com/a/38947571/14731 for an alternative answer. – Gili Aug 14 '16 at 23:37
  • Hum if you have uped your string and then test agains an upped prefix i can't see when this will fail. Ii seem's to me that's what 'standardise a string' means... I used it many times with no error in real life projects. – Nemesis Sep 12 '16 at 08:19
  • 16
    This answer is not true because toLowerCase() uses Locale.getDefault() internally to change the chars and that might lead to false negatives. Let's say you want to compare "İstanbul" with "istanbul". In Turkish "İ" s lower case equivalent is "ı". So when I try to do that `"İstanbul".toLowerCase().startsWith("istanbul".toLowerCase())` (in a Locale.Turkish environment), it will give me false. – Mustafa Berkay Mutlu Jan 29 '18 at 11:24
  • 3
    @Nemesis, This answer is wrong, having it as the accepted answer could be misleading for a lot of people. Would you please edit your answer and link to Rohit Jain answer. – Moha the almighty camel Jul 28 '19 at 16:42
  • This is a wrong answer since the original value should not be changed for a conditional function. – A.G. Sep 01 '23 at 00:15
102

One option is to convert both of them to either lowercase or uppercase:

"Session".toLowerCase().startsWith("sEsSi".toLowerCase());
This is wrong. See: https://stackoverflow.com/a/15518878/14731

Another option is to use String#regionMatches() method, which takes a boolean argument stating whether to do case-sensitive matching or not. You can use it like this:

String haystack = "Session";
String needle = "sEsSi";
System.out.println(haystack.regionMatches(true, 0, needle, 0, needle.length()));  // true

It checks whether the region of needle from index 0 till length 5 is present in haystack starting from index 0 till length 5 or not. The first argument is true, means it will do case-insensitive matching.


And if only you are a big fan of Regex, you can do something like this:

System.out.println(haystack.matches("(?i)" + Pattern.quote(needle) + ".*"));

(?i) embedded flag is for ignore case matching.

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • 1
    Actually, suppose there is a table which is having more than 1 lakh entries , and I use a for loop on particular column to parse all those entries and in that, I try to use this lowercase option above to search an entry starting with particular pattern. So, this is causing a performance issue. If there is no match found at all, then internally it will parse through all the entries, which will take lot of time, as simultaneously its getting converted to lowercase as well. So is there any other option, to resolve performance issue? – Sheetal Bhatewara Oct 08 '13 at 12:47
  • @Rohit Jain, actually this: `System.out.println("Session".toLowerCase().startsWith("sEsSi".toLowerCase()));` is not a propper solution. You can try this: `System.out.println("SessIon".toLowerCase().startsWith("sEsSi".toLowerCase()));` with vm arguments `-Duser.country=TR -Duser.language=tr` In this example the `I` is uppercase `i` – DPM Mar 02 '18 at 10:06
20

I know I'm late, but what about using StringUtils.startsWithIgnoreCase() from Apache Commons Lang 3 ?

Example :

StringUtils.startsWithIgnoreCase(string, "start");

Just add the following dependency to your pom.xml file (taking the hypothesis that you use Maven) :

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.11</version>
</dependency>
1
myString.toLowerCase().startsWith(starting.toLowerCase());
agad
  • 2,192
  • 1
  • 20
  • 32
1

try this,

String session = "Session";
if(session.toLowerCase().startsWith("sEsSi".toLowerCase()))
newuser
  • 8,338
  • 2
  • 25
  • 33
0

You can use String.search() function with regex that will give you the index of the first substring match of the search string. Then you can test the returned index to see if it is 0. 'i' at the end makes the search case insensitive.

const session = 'Session';
const startsWith = session.search(/sEsSi/i) === 0;
A.G.
  • 304
  • 2
  • 11
-1

You can use someString.toUpperCase().startsWith(someOtherString.toUpperCase())

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
-1
myString.StartsWith(anotherString, StringComparison.OrdinalIgnoreCase)
Procrastinator
  • 2,526
  • 30
  • 27
  • 36
TTTT
  • 9
  • 1
-3

You can always do

"Session".toLowerCase().startsWith("sEsSi".toLowerCase());
RamonBoza
  • 8,898
  • 6
  • 36
  • 48
-3

StartsWith(String value, bool ignoreCase, CultureInfo? culture) e.g:

string test = "Session";
bool result = test.StartsWith("sEsSi", true, null);
Console.WriteLine(result);

point: in VS by right-clicking on StartsWith and then "pick definition" can see all overloading method

enter image description here

enter image description here

pedram
  • 705
  • 7
  • 6