按两个字符串的顺序匹配的字符数

时间:2017-09-16 09:35:31

标签: java android

我想匹配两个字符串并获得按顺序匹配的字符数。 喜欢:

String one="ABCDEFGHIJK";
String two="ZANDEFGHOPQ";

你可以看到它必须按顺序返回5个字符,因为 DEFGH 存在于两个序列中。

由于

4 个答案:

答案 0 :(得分:1)

试试这个

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();

答案 1 :(得分:1)

也许这样的事情会做到。

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++;
    } 
}

答案 2 :(得分:1)

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);
    }
}

答案 3 :(得分:1)

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);      
}

}