【问题标题】:How to sort and remove duplicates from string Array without using the inbuilt function?如何在不使用内置函数的情况下从字符串数组中排序和删除重复项?
【发布时间】:2021-08-29 14:16:12
【问题描述】:

我想删除重复的字符串并对C#中的字符串数组进行排序我正在读取包含蓝色、绿色、红色、绿色、黄色等数据的文本文件,所以我正在使用File.ReadAllLines()读取数据,它返回一个数组字符串现在如何排序和删除重复。

private string[] sortArray(string[] str)
{
    int cnt = str.Length - 1;
    for (int i = 0; i < cnt; i++)
    {
        for (int j = cnt; j > i; j--)
        {
            if (((IComparable)str[j - 1]).CompareTo(str[j]) > 0)
            {
                var temp = str[j - 1];
                str[j - 1] = str[j];
                str[j] = temp;
            }
        }
    }
    return str;
}

使用上面的代码我可以对数组进行排序,但是如何删除重复的字符串 在此先感谢:)

【问题讨论】:

  • 冒泡排序,认真的吗?不使用内置方法的原因是什么?
  • 这能回答你的问题吗? Simple bubble sort c#
  • @Max :此代码也可以排序,但如何使用相同的循环从中删除重复项
  • @IvanStoev : 你有什么简单的解决方案可以提供最快的排序和删除重复项
  • 既然您已经可以对其进行排序,请检查 this 以删除重复项

标签: c# arrays sorting


【解决方案1】:

你可以这样做

List<string> colorList = new List<string> { "Yellow", "Blue", "Green", "Red", "Blue", "Green", "Red", "Green", "Green", "Yellow" };
colorList = colorList.Distinct().OrderBy(item=> item).ToList();

File.ReadAllLines() 会给你string[] 并且你可以像上面提到的一样应用DictinctOrderBy

在不使用内置函数的情况下排序和删除重复项

创建对此类方法的调用

string[] colorArray = new string[] { "Yellow", "Blue", "Green", "Red", "Blue", "Green", "Red", "Green", "Green", "Yellow" };
colorArray = RemoveDuplicates(colorArray);
Sort(colorArray);

使用下面的方法排序

static void Sort(string[] sa)
{
    int pos = 1;
    while (pos < sa.Length)
    {
        if (String.Compare(sa[pos], sa[pos - 1], StringComparison.OrdinalIgnoreCase) >= 0)
        {
            pos++;
        }
        else
        {
            string temp = sa[pos];
            sa[pos] = sa[pos - 1];
            sa[pos - 1] = temp;
            if (pos > 1) pos--;
        }
    }
}

使用这个删除重复项

static string[] RemoveDuplicates(string[] inputArray)
{

    int length = inputArray.Length;
    for (int i = 0; i < length; i++)
    {
        for (int j = (i + 1); j < length;)
        {
            if (inputArray[i] == inputArray[j])
            {
                for (int k = j; k < length - 1; k++)
                    inputArray[k] = inputArray[k + 1];
                length--;
            }
            else
                j++;
        }
    }

    string[] distinctArray = new string[length];
    for (int i = 0; i < length; i++)
        distinctArray[i] = inputArray[i];

    return distinctArray;

}

【讨论】:

  • 不使用内置函数想要从数组字符串中排序和删除重复项
  • @ketanpatil,试试上面提到的代码。这没有内置函数。
猜你喜欢
  • 2023-03-09
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多