Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare first three characters of two strings

Tags:

java

Strings s1 and s2 will always be of length 1 or higher.

How can I speed this up?

int l1 = s1.length();

if (l1 > 3) { l1 = 3; }

if (s2.startsWith(s1.substring(0,l1))) 
{
 // do something..
}

Regex maybe?

like image 840
nalo Avatar asked Feb 14 '10 16:02

nalo


People also ask

How do you compare characters in two strings?

You can compare two Strings in Java using the compareTo() method, equals() method or == operator. The compareTo() method compares two strings. The comparison is based on the Unicode value of each character in the strings.

What are the 3 ways to compare two string objects?

There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.

How do you compare the first n characters of two strings by ignoring the case?

tf = strncmpi( s1,s2 , n ) compares up to n characters of s1 and s2 , ignoring any differences in letter case. The function returns 1 ( true ) if the two are identical and 0 ( false ) otherwise.


1 Answers

This seems pretty reasonable. Is this really too slow for you? You sure it's not premature optimization?

like image 101
luiscubal Avatar answered Sep 22 '22 08:09

luiscubal