简体   繁体   English

如何比较两个字符串是否相同?

[英]How to compare whether two strings are identical?

So I'm doing this years Advent of Code and I'm stuck on the second day, part 2.所以我正在做今年的代码出现,我被困在第二天,第 2 部分。

You are given inputs which look like this:您会得到如下所示的输入:

 "1-3 c: caaasa"

You have to check how many passwords are valid due to the policy like, in above example:由于策略的原因,您必须检查有多少密码是有效的,例如上面的示例:

letter c has to be in position 1 OR 3 in the string caaasa .字母c必须在字符串caaasa中的 position 1 或 3 中。 If yes, the password is valid.如果是,则密码有效。

I've broken down that string to different sections, and now I try to compare a string "znak" which contains that given letter to a letter on position zakresmin and zakresmax in string "passdiv"我已经将该字符串分解为不同的部分,现在我尝试将包含给定字母的字符串"znak"字符串"passdiv"中 position zakresminzakresmax上的字母进行比较

Yet, everytime it returns False , so it doesn't add up to the count of passwords.然而,每次它返回False ,所以它不会加起来密码的数量。

I tried using Equals() and CompareTo() , but they don't seem to work.我尝试使用Equals()CompareTo() ,但它们似乎不起作用。

How can I modify my code so it returns proper values?如何修改我的代码以使其返回正确的值?

var iloschasel = 0;
using (StreamReader sr = new StreamReader(@"C:\Users\Wurf\Desktop\text.txt"))
{
   string line;
   while ((line = sr.ReadLine()) != null)
   {
      string[] linia = line.Split(" ");
      string zakres = linia[0];
      string[] zakresy = zakres.Split("-");
      int zakresmin = Convert.ToInt32(zakresy[0]);
      int zakresmax = Convert.ToInt32(zakresy[1]);
      string znak = (linia[1].Replace(":", "")).Trim();
      var suma = Regex.Matches(linia[2], znak);
      string passdiv = linia[2];
      if(passdiv[zakresmin].Equals(znak) || passdiv[zakresmax - 1].Equals(znak))
      {
         iloschasel += 1;
      }

   }
}
Console.WriteLine(iloschasel);

As mentioned, when you call Equals on two different types you are playing a game of chance with how the actual types are implemented.如前所述,当您在两种不同的类型上调用Equals时,您是在玩机会游戏,了解实际类型的实现方式。 In this case you lose.在这种情况下你输了。 Strings and chars will never have an equivalence or the same reference.字符串字符永远不会有等价或相同的引用。

I believe the compiler or resharper would give you a warning alerting you that neither type derive from string and char我相信编译器或resharper会给你一个警告,提醒你这两种类型都不是从stringchar派生的

However, I was bored enough to give an alternate solution但是,我很无聊,可以提供替代解决方案

public static bool IsValid(string input)
{
   var match = Regex.Match(input, @"(\d)-(\d) (\S): (.*)");
   if(!match.Success)
      throw new ArgumentException( $"Invalid format : {input}",nameof(input));

   var first = int.Parse(match.Groups[1].Value);
   var second = int.Parse(match.Groups[2].Value);
   var c = char.Parse(match.Groups[3].Value);
   var password = match.Groups[4].Value;

   return password[first-1] == c && password[second-1] == c;
}

Test测试

Console.WriteLine($"Is Valid = {IsValid("1-3 c: caaasa")}");
Console.WriteLine($"Is Valid = {IsValid("1-3 c: cacaasa")}");

Output Output

Is Valid = False
Is Valid = True

Note : this is not meant to be a complete bullet-proof solution.注意:这并不是一个完整的防弹解决方案。 Just a novel elegant way to solve your problem只是一种新颖优雅的方式来解决您的问题

Your problem is that you are comparing a string to a char您的问题是您正在将字符串与 char 进行比较

var match = "c" == 'c'; 

Will give a compile error because they are different data types会出现编译错误,因为它们是不同的数据类型

var match = "c".Equals('c');

will let you compile, but will always return false because a char will never equal a string.会让你编译,但总是返回 false,因为 char 永远不会等于字符串。 You have to turn the char into a string or visa versa for the check to work您必须将 char 转换为字符串或反之亦然才能使支票生效

var match = "c"[0] == 'c'; 

So in your if statement, if you fix the check to compare strings with strings or chars with chars you should get some positive results.因此,在您的 if 语句中,如果您修复检查以将字符串与字符串或字符与字符进行比较,您应该会得到一些积极的结果。 And also fix your indexing issue to decide if you want a 0 based index or a 1 based index with zakresmin and max并且还修复了您的索引问题,以决定您是想要一个基于 0 的索引还是一个基于 1 的带有 zakresmin 和 max 的索引

Also as a side note, it can be helpful to step through your code line by line in debug mode, to find out which line isn't behaving like you expect it to.另外作为旁注,在调试模式下逐行遍历代码会很有帮助,以找出哪一行的行为不像您期望的那样。 In your case debugging would have helped you zero in on the if statement as a starting point to fixing things.在您的情况下,调试将帮助您将 if 语句归零,作为修复问题的起点。

So it turns out (if I understand that correctly) that a compared element of the string passdiv was a char which I tried to compare to znak which was a string .所以事实证明(如果我理解正确的话)字符串passdiv的比较元素是一个char ,我试图将它与znak进行比较,它是一个string I added ToString() to my code and it works well.我将ToString()添加到我的代码中,它运行良好。 Also fixed the range of zakresmin by subtracting 1 so it works properly.还通过减去1来固定zakresmin的范围,使其正常工作。

if((passdiv[zakresmin - 1].ToString() == znak && passdiv[zakresmax - 1].ToString() != znak) || (passdiv[zakresmin - 1].ToString() != znak && passdiv[zakresmax - 1].ToString() == znak))
                    {
                        iloschasel += 1;
                    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM