kin*_*ode 1 c# arrays string unique
我关心的是将字符串添加到字符串数组中,但我想在插入数组之前确保该字符串是唯一的。我搜索并找到了很多方法,但我担心的是在添加字符串之前更快,而不是检查所有数组元素是否重复,所以我决定执行以下操作:
int index = 1;
int position = 0;
string s = Console.ReadLine();
byte[] ASCIIValues = Encoding.ASCII.GetBytes(s);
foreach(byte b in ASCIIValues)
{
position += b * index;
index++;
Console.WriteLine(b);
}
Run Code Online (Sandbox Code Playgroud)
正如评论中提到的, aHashSet将是用于这种情况的集合。它表示一组(唯一的)值并具有 O(1) 查找。因此,您只需循环要插入的字符串并将它们添加到集合中。如果字符串已经在那里,它将不会再次添加。
var set = new HashSet<string>();
foreach(var s in strings)
set.Add(s);
Run Code Online (Sandbox Code Playgroud)