如何使用C#检查字符或数字是否只使用一次?
有效:
abcdef
无效:
aabbccddeeff
用法示例:
string stringToTest = "tteesstt0011";
if (OnlyOnceCheck(stringToTest))
{
throw new Exception("Each character or number can be used only once");
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*zek 13
您可以使用LINQ:
public static bool OnlyOnceCheck(string input)
{
return input.GroupBy(x => x).Any(g => g.Count() > 1);
}
Run Code Online (Sandbox Code Playgroud)
或者Distinct:
public static bool OnlyOnceCheck(string input)
{
return input.Distinct().Count() == input.Length;
}
Run Code Online (Sandbox Code Playgroud)
更新
如果有人害怕性能,你可以随时使用HasSet<char>:
public static bool OnlyOnceCheck(string input)
{
var set = new HashSet<char>();
return input.Any(x => !set.Add(x));
}
Run Code Online (Sandbox Code Playgroud)
或者如果你害怕委托调用开销,你可以使用for循环:
public static bool OnlyOnceCheck(string input)
{
var set = new HashSet<char>();
for (int i = 0; i < input.Length; i++)
if (!set.Add(input[i]))
return false;
return true;
}
Run Code Online (Sandbox Code Playgroud)
但Any()在string做同样的事情...
| 归档时间: |
|
| 查看次数: |
4244 次 |
| 最近记录: |