【问题标题】:Comparing String To Array Element?将字符串与数组元素进行比较?
【发布时间】:2014-10-17 14:19:06
【问题描述】:

我有以下代码:

public class Equals {

        String[] s1 = {"red", "white", "black", "blue"};
        String[] s2 = {"red", "black", "green"};
        String[] s3 = {"red", "green"};

我需要的是给我以下输出:

比较字符串 s1、s2、s3

红色 3 匹配。 黑色 2 匹配。 绿色 2 匹配。

有人可以帮助我吗?

非常感谢!

您好!

【问题讨论】:

  • 你用的是什么语言
  • 你到底想做什么?是否要显示出现在两个以上数组中的任何元素?
  • java67.blogspot.com/2014/05/…这是你想要的吗?

标签: arrays string compare elements


【解决方案1】:

这不是很好,但可以快速解决您的要求。基本上,我将所有数组添加到一个 List 中,然后遍历该列表,检查所选元素是否与任何给定颜色匹配。

    public static void main(String[] args) 
    {
            String[] s1 = {"red", "white", "black", "blue"};
            String[] s2 = {"red", "black", "green"};
            String[] s3 = {"red", "green"};
            int red = 0;
            int black =0;
            int green = 0;
            int white= 0;
            int blue= 0;

            List <String> list = new ArrayList <String>();
            list.addAll(Arrays.asList(s1));
            list.addAll(Arrays.asList(s2));
            list.addAll(Arrays.asList(s3));

           for(String s: list)
           {
               if(s.equals("red"))
                {
                   red++;
                }
               else if(s.equals("white"))
                {
                   white++;
                }
               else if(s.equals("black"))
                {
                   black++;
                }
               else if(s.equals("green"))
                {
                   green++;
                }
               else  if(s.equals("blue"))
                {
                   blue++;
                }

           }
            System.out.println(red + "  Red found\n" + green + "  Green Found\n" + white + "  White Found\n" + black + "  Black Found\n" + blue + "  Blue Found");
    }
}

输出:

3  Red found
2  Green Found
1  White Found
2  Black Found
1  Blue Found

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多