Is the indexOf(String) method case sensitive? If so, is there a case insensitive version of it?
Yes, indexOf
is case sensitive.
The best way to do case insensivity I have found is:
String original;
int idx = original.toLowercase().indexOf(someStr.toLowerCase());
That will do a case insensitive indexOf()
.
Is the indexOf(String) method case sensitive?
Yes, it is case sensitive:
@Test
public void indexOfIsCaseSensitive() {
assertTrue("Hello World!".indexOf("Hello") != -1);
assertTrue("Hello World!".indexOf("hello") == -1);
}
If so, is there a case insensitive version of it?
No, there isn't. You can convert both strings to lower case before calling indexOf:
@Test
public void caseInsensitiveIndexOf() {
assertTrue("Hello World!".toLowerCase().indexOf("Hello".toLowerCase()) != -1);
assertTrue("Hello World!".toLowerCase().indexOf("hello".toLowerCase()) != -1);
}
@Test
public void testIndexofCaseSensitive() {
TestCase.assertEquals(-1, "abcDef".indexOf("d") );
}
The indexOf()
methods are all case-sensitive. You can make them case-insensitive by converting your strings to upper/lower case beforehand:
s1 = s1.toLowerCase(Locale.US);
s2 = s2.toLowerCase(Locale.US);
s1.indexOf(s2);
Yes, I am fairly sure it is. One method of working around that using the standard library would be:
int index = str.toUpperCase().indexOf("FOO");
Yes, it is case-sensitive. You can do a case-insensitive indexOf
by converting your String and the String parameter both to upper-case before searching.
String str = "Hello world";
String search = "hello";
str.toUpperCase().indexOf(search.toUpperCase());
I've just looked at the source. It compares chars so it is case sensitive.
indexOf is case sensitive. This is because it uses the equals method to compare the elements in the list. The same thing goes for contains and remove.
But it's not hard to write one:
public class CaseInsensitiveIndexOfTest extends TestCase {
public void testOne() throws Exception {
assertEquals(2, caseInsensitiveIndexOf("ABC", "xxabcdef"));
}
public static int caseInsensitiveIndexOf(String substring, String string) {
return string.toLowerCase().indexOf(substring.toLowerCase());
}
}
What are you doing with the index value once returned?
If you are using it to manipulate your string, then could you not use a regular expression instead?
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class StringIndexOfRegexpTest {
@Test
public void testNastyIndexOfBasedReplace() {
final String source = "Hello World";
final int index = source.toLowerCase().indexOf("hello".toLowerCase());
final String target = "Hi".concat(source.substring(index
+ "hello".length(), source.length()));
assertEquals("Hi World", target);
}
@Test
public void testSimpleRegexpBasedReplace() {
final String source = "Hello World";
final String target = source.replaceFirst("(?i)hello", "Hi");
assertEquals("Hi World", target);
}
}