2017-09-16 118 views
0

我想匹配兩個字符串並獲得按順序匹配多少個字符。 像:在兩個字符串的序列中匹配的字符數

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

就像你可以看到,它必須返回序列5個字符相匹配,因爲DEFGH兩個序列存在。

感謝

+1

的[簡單的方式將字符串中的字符數出現(可能的複製https://stackoverflow.com/questions/6100712/simple-way-to- count-character-occurrences-a-string) –

+0

@PratikTank我檢查了這一個,但問題是它只計算單個章程哪個用戶必須知道,它不符合我的需要 –

+1

可能重複的[查找字符出現次數在一個Java字符串](https://stackoverflow.com/questions/3763970/find-occurrences-of-c haracters-in-a-java-string) –

回答

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

謝謝@Nilesh讓我檢查這一個 –

+0

最歡迎@AmitSharma –

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

}

相關問題