简体   繁体   English

为什么这个 c# Palindrome 程序不起作用?

[英]Why is this c# Palindrome Program not working?

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Palindrome
{
    class Program
    {
        static void Main(string[] args)
        {


            string filePath = @"C:\Users\Me\Desktop\Palindromes\palindromes.txt";
            //This gets the file we need

            var meStack = new Stack<string>();
            //this  creates the stack

            foreach (var item in File.ReadLines(filePath))
            {
                meStack.Push(item.ToUpper());
            }
            //for every item in the file, push onto the stack and make it upper case


            while (meStack.TryPop(out string Line))
            {
                reverseMe(Line);
            }
            //While every line in the stack is popped out, every line goes to the fucntion reverseMe






            static bool reverseMe(string Line)
            {
                return
                    Line == Line.Reverse();
            }
            //return true if line is the same as the line backwards or false if its not.


        }
    }

}

How do I get output?我如何获得输出? I have written comments to try and understand... but I am not getting a console output.我已经写了评论来尝试理解......但我没有得到控制台输出。 I want the code to take in the file, put all the strings into a stack, and send every line in that stack to the reverseMe() function, which is a bool.我希望代码接收文件,将所有字符串放入一个堆栈中,并将该堆栈中的每一行发送到 reverseMe() 函数,它是一个布尔值。 The bool will see if the string is the same forward as it is backwards and if so it will return true or false. bool 将查看字符串向前和向后是否相同,如果是,它将返回 true 或 false。 Basically my console is empty when I try to run this code.. What do I do?基本上,当我尝试运行此代码时,我的控制台是空的。我该怎么办?

There is a problem in the method reverseMe , The function Reverse gives you collection of char if applied on string , then you need to convert IEnumerable<char> to string by new string() or string.Concat() , like the following code:方法reverseMe有问题,如果应用于string ,则函数Reverse为您提供char集合,然后您需要通过new string()string.Concat()IEnumerable<char>转换为string ,如下面的代码:

static bool reverseMe(string Line)
{
    //deleting whitespaces, tabs
    Line = Regex.Replace(Line, @"\s+", "");

    return Line == new string(Line.Reverse().ToArray());
    //or
    //return Line == string.Concat(Line.Reverse());
    //or like Dmitry comment
    //return Line.SequenceEqual(Line.Reverse());
}

Calling reverseMe , and output result like : word is not palindrome调用reverseMe ,输出结果如word is not palindrome

while (meStack.TryPop(out string Line))
{
    string isOrNotPalindrome = reverseMe(Line) ? string.Empty : "not";
    Console.WriteLine($"{Line} is {isOrNotPalindrome} palindrome");
}

Demo演示

bool isPalindrome1 = reverseMe("madam");
bool isPalindrome2 = reverseMe("nurses run");
bool isPalindrome3 = reverseMe("AaBbbBaAp");

Result结果

true
true
false

I hope this will help you fix the issue我希望这能帮助您解决问题

Let's start from the problem;让我们从问题开始; I assume that you want to scan all file's lines and print out if the line is a palindrom.我假设您想扫描所有文件的行并打印出该行是否为回文。

First, we need to implement IsPalindrom method:首先,我们需要实现IsPalindrom方法:

private static bool IsPalindrom(string value) {
  if (null == value)
    return false; // or true, ot throw ArgumentNullException

  // We have to prepare the string: when testing for palindrom
  //  1. Let's ignore white spaces (' ', '\r', '\t' etc.)
  //  2. Let's ignore punctuation  (':', ',' etc.)
  //  3. Let's ignore cases        (i.e. 'M' == 'm') 
  // So "Madam, I'm Adam" will be a proper palindrom
  value = string.Concat(value
    .Where(c => !char.IsWhiteSpace(c))
    .Where(c => !char.IsPunctuation(c))
    .Select(c => char.ToUpperInvariant(c)));

  // Instead of Reversing we can just compare:
  // [0] and [Length - 1] then [1] and [Length - 2] etc.
  for (int i = 0; i < value.Length / 2; ++i)
    if (value[i] != value[value.Length - 1 - i])
      return false; // we have a counter example: value is NOT a palidrom

  // Value has been scanned, no counter examples are found
  return true;    
}

Time to write Main method:编写Main方法的时间:

static void Main(string[] args) {
  string filePath = @"C:\Users\Me\Desktop\Palindromes\palindromes.txt";

  var result = File
    .ReadLines(filePath)
    .Where(line => !string.IsNullOrWhiteSpace(line)) // let's skip empty lines
    .Select(line => $"{(IsPalindrom(line) ? "Palindrom" : "Not a palindrom")}: \"{line}\"");

  // Do not forget to print result on the Console:
  foreach (var record in result)   
    Console.WriteLine(record);

  // Pause to have a look at the outcome (wait for a key to be pressed)
  Console.ReadKey(); 
} 

嗯,从 reverseMe() 函数获得结果后,没有 Console.WriteLine() 来执行任何实际输出。

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

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