数组中没有重复项 [英] no duplicates in array

查看:77
本文介绍了数组中没有重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我有一个句子分配文件.我需要用该文件中的单词制作字典.到目前为止,我已经分离出单词并使用Split()Sort()方法对它们进行了排序.我的问题是制作没有重复单词的列表.我该怎么办?

Hi there

I have a file with allot of sentences. I need to make a dictionary with the words from that file. Until now I''ve separated the words and sort them using Split() and Sort() methods. My problem is to make a list without duplicate words. How can I do that?

static int n = 0;

public static string[] NoDuplicate(string[] array)
{
    int i;
    string[] res = (string[])array.Clone();
    for (i = 0; i < array.Length-1; i++)
	{
        if (array[i + 1] != array[i])
            res[n++] = (string)array[i];
	}
    return res;
}



1)我该如何做得更整洁?
2)我不喜欢这种方法,因为它是使用Clone()初始化的,并且长度太大.

many thx



1) how can I do it more neat?
2) i don''t like that method because is initialized using Clone() and the length is too big.

many thx

推荐答案

看看 HashSet< String> [ ^ ]类(仅.net 3.5).它提供了优化的哈希集合,并且不允许重复(它只是忽略添加重复的尝试),如果确实需要字符串数组,则可以在完成后调用ToArray().
Take a look at the HashSet<String>[^] class (.net 3.5 only). It provides an optimised hash collection and it doesn''t allow duplicates, (it just ignores attempts to add duplicates), and you can call ToArray() when you are done with it if you really need a string array.


这是您使用HashSet的代码:
Here is your code using HashSet:
public static string[] RemoveDuplicates(string[] s)
{
    HashSet<string> set = new HashSet<string>(s);
    string[] result = new string[set.Count];
    set.CopyTo(result);
    return result;
}
</string></string>


您也可以过滤输入的数组,避免定义谓词.

如果输入的数组不为null,则该方法分配List<string>.

如果未事先插入每个元素,则迭代地填充分配的集合(保持线性复杂度).

最后,对集合进行排序并将其转换为string[]

You can also filter the inputted array avoid defining a predicate.

If the inputted array is not null, the method allocates a List<string>.

The allocated collection is filled iteratively (maintaining the linear complexity) adding each element if it has not been not prevously inserted.

Finally, the collection is sorted and converted to string[]

public static string[] NoDuplicate(string[] inputSentences)
{
    if (inputSentences == null)
        return inputSentences;

    Debug.Assert(inputSentences != null);

    List<string> sentences = new List<string>();

    foreach (string inputSentence in inputSentences)
    {
        if (sentences.Contains(inputSentence) == true)
            continue;

        sentences.Add(inputSentence);
    }

    Debug.Assert(sentences != null);
            
    sentences.Sort();
    return sentences.ToArray();
}


这篇关于数组中没有重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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