在C#中字谜功能的实现 [英] Implementation of an anagram function in C#

查看:116
本文介绍了在C#中字谜功能的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
什么是简单的方法来判断一个单词列表互为字谜?

什么是最好的方式(性能宽)写在C#中采用两个函数字符串,返回true当字符串是彼此的字谜否则,返回假。字谜的例子是:

What is the best way (performance wide) to write a function in C# that takes two strings and returns true when the strings are anagrams of each other and otherwise returns false. Example of anagrams are:

abet beat beta bate
abides biased

字谜链接

在实现这一点,是有可能,有空间在每个字符串?

In implementing this, is it possible that there is space in each string?

任何想法会非常感谢!

推荐答案

这是简单的解决办法是将人物按字母顺序排序,并比较它们彼此。

An easy solution would be to sort the characters alphabetically and compare them to one another.

public static class AnagramExtensions
{
    public static bool IsAnagramOf(this string word1, string word2)
    {
        return word1.OrderBy(x => x).SequenceEqual(word2.OrderBy(x => x));
    }
}



然后,要使用它:

Then, to use it:

    static void Main()
    {
        string word1 = "cat";
        string word2 = "tac";

        Console.WriteLine(word1.IsAnagramOf(word2));

        string word3 = "cat";
        string word4 = "dog";

        Console.WriteLine(word3.IsAnagramOf(word4));
    }   



在这种情况下,输出将是

The output in this case would be

这篇关于在C#中字谜功能的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆