2013-10-04 190 views
0

在這個java程序中一切正常,但最後我必須得到字符長度匹配的字數,但我不能如何得到它?java中字符串的常見長度

Scanner input = new Scanner(System.in); 

String s1 = "Enter the name 1:"; 
System.out.println(s1); 
s1 = input.next(); 

String s2 = "Enter the name 2:"; 
System.out.println(s2); 
s2 = input.next(); 

if (s1.equals(s2)) { 
    System.out.println("They match"); 
} else { 
    System.out.println("They dont match"); 
} 

char[] c = s1.toCharArray(); 
char[] d = s2.toCharArray(); 

for (char i = 0; i < c.length; i++) { 
    for (char j = 0; j < d.length; j++) { 
     if (c[i] == d[j]) { 
      System.out.println("The number of letters matched are :" + c[i]); 
     } 

    } 
} 
System.out.println("The number of letters matched are :" + c.length); 
+5

縮進你最好的朋友。或者他們應該是。 – Tommy

+1

你的意思是說你必須得到「字符長度匹配的字數」,但是你的代碼試圖計算兩個字符串有共同的字符數,這是不完全相同的事情。下定決心! – ccdan

回答

1

使用計數器

int counter = 0 ; 
for (char i = 0; i < c.length; i++) { 
    boolean found = false; 
    for (char j = 0; j < d.length; j++) { 
     if (c[i] == d[j]) { 
      found = true; 
      System.out.println("The number of letters matched are :" + c[i]); 
      break; 
     } 
    } 
    if(found){ 
     counter++; 
    } 
} 
System.out.println("The number of letters matched are :" + counter); 
+0

這將給出9輸入'aaa'和'aaa',我不認爲這是OP – justhalf

0
char[] c = s1.toCharArray(); 
char[] d = s2.toCharArray(); 
int count = 0; 
for (char i = 0; i < c.length; i++) { 
    for (char j = 0; j < d.length; j++) { 
     if (c[i] == d[j]) { 
      count++; 
     } 
    } 

} 

System.out.println("The number of letters matched are :" + count); 

我認爲這是你在找什麼。

您需要計算循環中的匹配數,然後循環後顯示兩個數組中的字母數。

+0

的預期含義,這將給出輸入aaa和aaa的9,我不認爲這是OP的預期含義 – justhalf

0

如果目標是獲取兩個字符串之間的通用字符數,則一種方法是將兩個字符串轉換爲字符集,並在兩個集之間設置交集並獲取其大小。

0

如果你想的次數在S1人物也出現在S2:

int counter = 0; 
for (int i=0; i<s1.length(); i++) { 
    if (s2.indexOf(s1.charAt(i)) >= 0) { 
    counter++; 
    } 
} 
System.out.println("The number of letters matched are :" + counter); 

相反,如果你想通過共享的不同字符數S1和S2:

Set<Character> set = new HashSet<>(); 
int counter = 0; 
for (int i=0; i<s1.length(); i++) { 
    set.add(s1.charAt(i)); 
} 
for (int j=0; j<s2.length(); j++) { 
    if (set.contains(s2.charAt(j))) { 
    counter++; 
    } 
} 
System.out.println("The number of letters matched are :" + counter);