【发布时间】:2014-02-25 00:19:06
【问题描述】:
public class StringEx {
public static void main(String[] args){
String s1 ="abcc";
String s2 = "cbaa";
getCommon(s1,s2);
}
private static void getCommon(String s1, String s2) {
char[] c1 = s1.toCharArray();
char[] c2 = s2.toCharArray();
char[] commonAry = new char[10];
for(int i=0;i < (c1.length)-1;i++){
for(int j=0;j<(c2.length)-1;j++){
if(c1[i]==c2[j]){
int k=0;
commonAry[k]=c1[i];
k++;
}
}
}
System.out.println(commonAry);
}
}
上面的程序给出的输出类似于“c n some square boxer after that”.. 上面的代码有什么问题。
【问题讨论】:
-
您希望
System.out.println(commonAry);做什么?为什么? -
commonAry的长度应该是 =min(c1.length, c2.length)。你的老师会给char[10]减分 -
回答完我上面的问题后,请阅读this。
-
k 永远不会超过 0,可能也考虑到这一点
-
将一个单词的字母放入一个 Set 中,然后遍历另一个单词并检查每个字母是否存在。
标签: java