Reputation: 936
I want to match two string and get how many chars matched in sequence. Like :
String one="ABCDEFGHIJK";
String two="ZANDEFGHOPQ";
like you can see that it must return 5 chars in sequence matched because DEFGH are exist on both sequence.
Thanks
Upvotes: 0
Views: 1053
Reputation: 101
I know it is a rather old question, but perhaps someone will find this "if-less" answer a nice one. One can shorten it a bit further by replacing len in the loop by its definition.
public class TestClass {
public static void main(String[] args) {
String one = "ABCDEFGHIJK";
String two = "ZANDEFGHOPQ";
int len = Math.min(one.length(), two.length());
int counter = 0;
for (int i = 0; i < len; i++) {
counter += (one.charAt(i) == two.charAt(i)) ? 1 : 0;
}
System.out.println(counter);
}
}
Upvotes: 0
Reputation: 44329
Maybe something like this will do it.
String one="ABCDEFGHIJK";
String two="ZANDEFGHOPQ";
int counter = 0;
// Iterate over the string character by character - stop when reaching the
// end of the shortest string
for( int i=0; i<one.length() && i<two.length(); i++ ) {
// Compare the strings character at the current position/index
if(one.charAt(i) == two.charAt(i)) {
// The characters matched so increment the counter
counter++;
}
}
Upvotes: 1
Reputation: 69709
try this
String one="ABCDEFGHIJK";
String two="ZANDEFGHOPQ";
int cnt=0;
for (int i=0;i<one.length();i++){
for (int j=0;j<two.length();j++){
if(one.charAt(i) == two.charAt(j) ){
cnt++;
}
}
}
Toast.makeText(this, "count"+cnt, Toast.LENGTH_SHORT).show();
Upvotes: 1
Reputation:
public class Test {
public static void main(String[] args) {
String one="ABCDEFGHIJK";
String two="ZANDEFGHOPQ";
int size1 = one.length();
int size2 = two.length();
int i = 0;
int j = (size1 >= size2 ? size2 : size1);
char[] oneTab = one.toCharArray();
char[] twoTab = two.toCharArray();
int k = 0;
for(i = 0; i< j; i++){
if((String.valueOf(oneTab[i])).equals(String.valueOf(twoTab[i]))){
k = k+1;
};
};
System.out.println(k);
}
}
Upvotes: 1
Reputation: 2159
import java.io.*;
import java.util.*;
class happy {
public static void main(String args[])
{
String one="ABCDEFGHIJK";
String two="ZANDEFGHOPQ";
int a=0,c=0;
if(one.length()<two.length())
a=one.length();
else
a=two.length();
for(int i=0;i<a;i++)
{
if(one.charAt(i)==(two.charAt(i)))
c++;
}
System.out.println(c);
}
}
Upvotes: 1