简体   繁体   English

这段代码有什么区别

[英]What's the difference between this code's

I'm trying to check a palindrome string, which one do you thing is better?我正在尝试检查回文字符串,您认为哪个更好?

I created a bool function to check the Palindrome and then in Main we implemented the user input along with the if statement which checks if bool1 is true or false determining the output, respectively if the string is a palindrome or not.我创建了一个 bool function 来检查回文,然后在 Main 中我们实现了用户输入以及 if 语句,该语句检查 bool1 是真还是假,分别确定字符串是否为回文。

public static bool Palindrome(string text)

{
   if (text.Length <= 1)
      return true;
   else
   {
      if ( text[0] != text[ text.Length - 1 ] )
           return false;
      else
           return Palindrome( text.Substring( 1, text.Length-2 ) );
   }   
   }   
public static void Main()

{

   string userInput;
   bool bool1;
        
   Console.Write(" Input a string : ");
   userInput = Console.ReadLine();
   bool1 = Palindrome(userInput);
   if (bool1 ==true)
   {
      Console.WriteLine(" The string is Palindrome.");
   }
   else
   {
      Console.WriteLine(" The string is not a Palindrome.");
   }
}

or this one或者这个

static void Main(string[] args)

{
    Console.WriteLine("Please input a string");
    string userString = Console.ReadLine();
    string userOutput = Reversed(userString);
    bool res = CheckPalindrome(userString, userOutput);

    Console.ReadKey();
    }

 static string Reversed(string userString)

 {
    char[] reveresed = userString.ToCharArray();
    Array.Reverse(reveresed);
    string userOutput = new string(reveresed);
    return userOutput;
 }

    static bool CheckPalindrome(string userOutput, string userString)
    {
        bool bool1 = userString.Equals(userOutput, StringComparison.OrdinalIgnoreCase);
        if (bool1 == true)
        {
            Console.WriteLine("The string " + userOutput + " is a Palindrome!");
        }
        else
        {
            Console.WriteLine("The string " + userOutput + " is not a Palindrome!");
        }
        return bool1;
    }

As @TimSchmelter said, the second version is faster and more readable.正如@TimSchmelter 所说,第二个版本更快,更具可读性。

There is however, a faster if more complex, version than either of those two.但是,有一个比这两个版本中的任何一个都更快但更复杂的版本。

Loop through the first half of the string, and compare it with the second half.循环遍历字符串的前半部分,并将其与后半部分进行比较。 The middle character in an odd-numbered length will be ignored.奇数长度的中间字符将被忽略。

bool IsPalindrome(string myString)
{
    if (string.IsNullOrEmpty(myString))
        return false;
    for (var i = 0; i < myString.Length / 2; i++)
    {
        if(myString[i] != myString[myString.Length - i - 1])
            return false;
    }
    return true;
}

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

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