【问题标题】:Create a new string that will consist of common letters from other two strings in java创建一个新字符串,该字符串将由 java 中其他两个字符串的常用字母组成
【发布时间】: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


【解决方案1】:

使用Set&lt;character&gt;retainAll()方法获取两个String的交集

public static void getCommon(String s1,String s2){


         char[] s1Array = s1.toCharArray();  
         char [] s2Array = s2.toCharArray();  


     Set<Character>s1CharSet = new HashSet<Character>();  
     Set<Character>s2CharSet = new HashSet<Character>();  

     for(char c:s1Array){  
         s1CharSet.add(c);  
     }  

     for(char c: s2Array){  
         s2CharSet.add(c);  
     }  

     s1CharSet.retainAll(s2CharSet);  

     if(s1CharSet.size()==0){  
        System.out.println("There are no common characters between the two strings");  
     }  

     else{  
         System.out.println(s1CharSet);  
     }  


     }  

输出

  [b, c, a]

Demo

【讨论】:

  • 你真的运行了这个,并得到"abc"作为输出?
  • @DavidWallace 是的,我得到 abc 作为输出并添加演示链接检查它
  • 好的。您确实意识到使用不同的输入字符串,这不会很好地解决,对吧?使用此特定输入时,至少存在三个巧合未能显现的错误。
  • @DavidWallace 谢谢,当我尝试使用 == 比较器时,我发现了困难,所以我尝试了设置中的 retainAll 方法,你能检查我编辑的答案..
  • 现在看起来好多了,好多了;据我所知,它工作正常。请注意,您不需要自己遍历 char 数组来制作集合。你可以写Set&lt;Character&gt; s1CharSet = new HashSet&lt;Character&gt;(Arrays.asList(s1Array));
【解决方案2】:

首先,你没有循环遍历所有的 char 数组,你的循环 应该是:

for(int i=0;i < (c1.length);i++)

其次,您必须从循环中初始化索引 k, 第三,这个操作是不可交换的,也就是说

getCommon(String s1, String s2)

getCommon(String s2, String s1)

不会给出相同的结果,

最后,因为你想得到常见的字母,所以为什么不呢 在 其他数组?

【讨论】:

    猜你喜欢
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    相关资源
    最近更新 更多