如何测试字符串是否仅由不同的字符组成?
How can I test if a string is made up from different characters only?
我有一个来自 Console.Readline()
的 5 个字符长的字符串,我想测试这 5 个字符是否都不同。
您可以使用 Distinct
方法,该方法将为您提供不同的字符,然后只需将计数与输入 length
进行比较,如果它们相等,则表示所有字符都不同。
string input = Console.ReadLine();
bool isDifferent = input.Distinct().Count() == input.Length;
请注意,您需要 using System.Linq;
才能使用 Distinct
方法。
我有一个来自 Console.Readline()
的 5 个字符长的字符串,我想测试这 5 个字符是否都不同。
您可以使用 Distinct
方法,该方法将为您提供不同的字符,然后只需将计数与输入 length
进行比较,如果它们相等,则表示所有字符都不同。
string input = Console.ReadLine();
bool isDifferent = input.Distinct().Count() == input.Length;
请注意,您需要 using System.Linq;
才能使用 Distinct
方法。