【问题标题】:Why is this c# Palindrome Program not working?为什么这个 c# Palindrome Program 不起作用?
【发布时间】:2020-07-01 00:41:37
【问题描述】:
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.


        }
    }

}

如何获得输出? 我已经编写了 cmets 来尝试理解......但我没有得到控制台输出。我希望代码接收文件,将所有字符串放入堆栈,并将堆栈中的每一行发送到 reverseMe() 函数,这是一个布尔值。 bool 将查看字符串是否向前和向后相同,如果是,它将返回 true 或 false。基本上,当我尝试运行此代码时,我的控制台是空的。我该怎么办?

【问题讨论】:

  • 程序应该做什么?我看不到任何输出。您可能想要添加 Console.WriteConsole.WriteLine 以在控制台上写入内容
  • 这是一个调试问题,请在提问前先学习如何使用调试器,然后当你无法理解某些内容时,将这些信息带到问题中,你期望发生什么,正在发生什么,它发生了什么。
  • static bool IsPalindrome(string input) { return input.SequenceEqual(input.Reverse()); } 应该可以工作,因为您正在尝试将 IEnumerablesReverse 进行比较

标签: c# output comments palindrome


【解决方案1】:

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

【讨论】:

  • 这不是答案。请使用 cmets 的问题(或答案)的评论部分。另请注意,可以通过其他方式检查值,例如在调试器中使用断点。
【解决方案2】:

方法reverseMe有问题,函数Reverse给你char的集合如果应用于string,那么你需要将IEnumerable&lt;char&gt;转换为stringnew string()string.Concat(),如以下代码:

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());
}

调用reverseMe,输出结果类似word is not palindrome

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

演示

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

结果

true
true
false

我希望这将帮助您解决问题

【讨论】:

  • return Line.SequenceEquals(Line.Reverse());
  • 没错,但SequenceEquals 最后没有s :),我还删除了空格,以测试像这样nurses run 的字符串。非常感谢!
  • 删除空白空格(不仅仅是普通空格,还包括制表符、换行符等):Line = Regex.Replace(Line, @"\s+", "");
  • @Marvin 如果我理解正确,我更新了我的答案,添加了while 循环。如果它对您有用,请点赞并接受答案,以便其他人会发现它有用
【解决方案3】:

让我们从问题开始;我假设您要扫描文件的所有行并打印出该行是否为回文。

首先,我们需要实现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;    
}

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(); 
} 

【讨论】:

    猜你喜欢
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 2013-03-10
    • 1970-01-01
    相关资源
    最近更新 更多