C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Case: We can have regionMatches ignore the case of characters by passing a value of "true" as the first argument.
Java program that uses regionMatches
public class Program {
public static void main(String[] args) {
String codes = "onetwothreeFour";
// Check for "two" at index 3.
// ... Length is 3 chars.
if (codes.regionMatches(3, "two", 0, 3)) {
System.out.println(true);
}
// Check for "three" at index 6.
// ... Length is 5 chars.
if (codes.regionMatches(6, "three", 0, 5)) {
System.out.println(true);
}
// Check for "FOUR" from "IS_FOUR" at index 11.
// ... Length is 4 chars.
if (codes.regionMatches(true, 11, "IS_FOUR", 3, 4)) {
System.out.println(true);
}
}
}
Output
true
true
true
Version 1: In this version of the code, we use the regionMatches method to compare 2 substring parts.
Version 2: In this code we make two substring calls. Those substrings are compared with equals().
EqualsResult: RegionMatches is faster. In this benchmark regionMatches is over 10 times faster than the version that uses substring and equals.
Java program that benchmarks regionMatches
public class Program {
public static void main(String[] args) {
String part1 = "catdogbird";
String part2 = "dogbirdcat";
// Test two versions.
if (part1.regionMatches(3, part2, 0, 3)) {
System.out.println("True 1");
}
if (part1.substring(3, 6).equals(part2.substring(0, 3))) {
System.out.println("True 2");
}
int count = 0;
long t1 = System.currentTimeMillis();
// Version 1: use regionMatches to compare two substrings.
for (int i = 0; i < 10000000; i++) {
if (part1.regionMatches(3, part2, 0, 3)) {
count++;
}
}
long t2 = System.currentTimeMillis();
// Version 2: use substring to compare two substrings.
for (int i = 0; i < 10000000; i++) {
if (part1.substring(3, 6).equals(part2.substring(0, 3))) {
count++;
}
}
long t3 = System.currentTimeMillis();
// ... Times.
System.out.println(count);
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
Output
True 1
True 2
20000000
15 ms: regionMatches
172 ms: substring, equals