简体   繁体   English

使用if来比较字符串c#

[英]Using if to compare strings c#

I am trying to compare strings then have it write hi if the strings are equal.我试图比较字符串然后让它写 hi 如果字符串相等。 But whenever I enter AS I get nothing AS being the string i want to compare my input against.但是每当我输入 AS 时,我什么也得不到,因为我想将我的输入与之进行比较。

Here is my code.这是我的代码。

using System;

namespace testing121
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            long vrt;
            bool run;
            string pass = ("AS");
            run = true;
            string vrt2;
            while (run)
            {
                if (long.TryParse (Console.ReadLine (), out vrt)) {
                    vrt2 = Convert.ToString (vrt);
                    if (String.Equals (pass, vrt2) ) {
                        Console.WriteLine ("Hi");
                    }
                }
            }}}}

This code just doesn't make sense.这段代码没有意义。 You're entering AS but then checking if it can be converted to a long as part of your condition for equality.您正在输入AS ,然后检查它是否可以转换为long作为您的平等条件的一部分。 Just do this;就这样做;

public static void Main (string[] args)
{
   string pass = "AS";

   if (Console.ReadLine() == pass)
       Console.WriteLine("hi");
}

Then, if you want to put that in a loop or whatever go for it.然后,如果你想把它放在一个循环中或其他任何地方。 But I recommend starting with the simplest most basic thing.但我建议从最简单的最基本的东西开始。 When you run this program and enter AS it will print hi当你运行这个程序并输入AS它会打印hi

Because when you check your if (long.TryParse (Console.ReadLine (), out vrt)) the result of the TryParse is always False as you don't provide a number as long.因为当您检查if (long.TryParse (Console.ReadLine (), out vrt))时, TryParse的结果始终为False因为您没有提供那么长的数字。 And the console will not write you Hi .并且控制台不会写你Hi

You can also do this...你也可以这样做...

string pass = "AS";

            if (pass.Equals(Console.ReadLine()))
            {
                Console.WriteLine("hi");   
            }

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

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