这是个问题:
"编写一个程序,从文本中提取所有的回文词,如ABBA","lamal","exe"."
这是我的代码:
public static List<string> FindPalindromes()
{
string text = String.Empty;
Console.Write("Enter the text:\n\t");
text = Console.ReadLine();
List<string> answer = new List<string>();
string[] words = text.Split('.', ',', ' ', ':', '/', '\\', '"', ';');
foreach(string word in words.Where(
(string x) =>
{
if(String.Equals(x, x.Reverse()))
return true;
else
return false;
}
))
answer.Add(word);
return answer;
}
Run Code Online (Sandbox Code Playgroud)
现在我认为如果我将where方法中的逻辑分离为一个返回布尔值并检查单个单词是否为回文的单独方法,它会更加整洁.但我想尝试使用lambda.
无论如何,这段代码不会返回任何内容.我怀疑问题出在if条件中.
x.Reverse()正在调用Enumerable.Reverse(),它将返回IEnumerable<char>- 而不是字符串.这Equals就是永不回归的原因true.这是另一种选择:
char[] chars = x.ToCharArray();
Array.Reverse(chars);
return x == new string(chars);
Run Code Online (Sandbox Code Playgroud)
或者你可以只调用string.Join或string.Concat反转相反的字符序列 - 非常低效,但它可以在一个表达式中完成工作,允许您通过以下方式替换以后的所有内容foreach:
return words.Where(x => x == string.Concat(x.Reverse())
.ToList();
Run Code Online (Sandbox Code Playgroud)
更清洁:)任何时候你发现自己反复添加到列表,考虑使用查询和ToList().你已经有了过滤部分,你只需要用来ToList()摆脱foreach循环.
同样,任何时候你发现自己:
if (condition)
return true;
else
return false;
Run Code Online (Sandbox Code Playgroud)
... 强烈考虑重构:
return condition;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
188 次 |
| 最近记录: |