【问题标题】:Identify if all values are same within a string [closed]确定字符串中的所有值是否相同[关闭]
【发布时间】:2015-01-14 05:44:56
【问题描述】:

嗯,我被一些非常基本的东西难住了。我有一个带有一组逗号分隔值的字符串。本质上是这样的:

public string shapes = circle, circle, square;

这个例子最终会在一个布尔值中返回一个false 值,因为所有 3 个值都不匹配。

我正在寻找最简单的方法来比较一个字符串中的值。到目前为止,我只看到了比较 2 个或更多字符串的方法。我希望我可以做到这一点,而不必诉诸于填充列表或数组。

【问题讨论】:

  • 你应该发布一些代码。你试过什么?
  • 请检查您的问题并尝试更清楚地了解您想要实现的目标。究竟什么会“在布尔值中返回错误值”?如果您需要分隔一个字符串中的值,您应该查看 String.Split link

标签: c# string csv compare


【解决方案1】:
static bool ShapeCheck(string shapeString)
{
    var shapes = shapeString.Split(new[] { ',' , ' ' }, StringSplitOptions.RemoveEmptyEntries);
    return shapes.Distinct().Count() == 1;
}

你可以这样称呼它:

Console.WriteLine("circle, circle, square = {0}", ShapeCheck("circle, circle, square"));
Console.WriteLine("circle, circle, circle = {0}", ShapeCheck("circle, circle, circle"));

第一个为假,第二个为真。

【讨论】:

    【解决方案2】:

    您需要使用带有逗号作为分隔符的Split 函数。

    然后假设有前导或尾随空格(如您的示例所示),您将需要 Trim

    现在你有一个来自字符串的填充值集合。

    然后你可以使用Linq 并做一个Distinct 并检查长度,如果长度改变了,有重复。

    这是假设您不想知道已复制的内容。

    【讨论】:

      【解决方案3】:

      您可以在string[] 上拨打Distinct()

          static void Main(string[] args)
          {
              var str = "foo,bar,test";
              Console.WriteLine(DoValuesMatch(str));
              Console.ReadLine();
          }
      
          private static bool DoValuesMatch(string str)
          {
              var strArr = str.Split(new[] { ',' });
              return strArr.Distinct().Count() == 1;
          }
      

      【讨论】:

      • 谢谢大家!这些都是很好的方法。我认为约翰的答案是我一直在寻找的,但很高兴知道还有其他方法。
      【解决方案4】:

      既然已经采用了所有很酷的标准答案...一种老派的方法:

          public string shapes = "circle, circle, square";
      
          private void button1_Click(object sender, EventArgs e)
          {
              shapes = shapes + ",";
              int comma = shapes.IndexOf(",");
              string value = shapes.Substring(0, comma).Trim();
              shapes = shapes.Replace(value, "").Trim(", ".ToCharArray());
              bool AllTheSame = (shapes.Length == 0);
              if (AllTheSame)
                  Console.WriteLine("They are all: " + value);
              else
                  Console.WriteLine("They are NOT all the same.");
          }
      

      【讨论】:

        猜你喜欢
        • 2013-04-08
        • 2017-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-10
        • 2015-03-30
        相关资源
        最近更新 更多