从字符串数组中删除相邻的重复字符串?

时间:2017-02-18 07:40:58

标签: c++ arrays string duplicates

这是我写的文本文件:

this is the first line
this is the first line
this is the second line
this is the second line
this is the second line
this is the third line
this is the first line

我正在尝试删除相邻的重复字符串,因此输出将是:

this is the first line
this is the second line
this is the third line
this is the first line

这是我到目前为止所写的:

for(int i = 0; i < n; i++)
getline(infile,arr[i]);

for(int i=0; i<n; i++)
{
        int j = i+1;
        if(arr[i] == arr[j])
        {
                for(int k = i; k<n; k++)
                arr[k] = arr[k+1];
                n--;
        }
}

这是我得到的输出:

this is the first line
this is the second line
this is the second line
this is the third line
this is the first line

如何解决这个问题? P.S。:它必须迭代地解决,这就是我试图这样做的原因。

3 个答案:

答案 0 :(得分:2)

如果同一行的重复次数超过2个,则会出现问题。在您的情况下,这会导致问题。

this is the second line
this is the second line
this is the second line

问题是你只能用下一个元素去除一行。

实施例: 如果你有4行,其中第1,2,3行是重复的,你会:

  1. 将1与2进行比较,然后删除2,将数组压缩为1,3

  2. 不是将1与3进行比较,而是跳过将3与4进行比较(错误)

  3. 为了修复您的解决方案,您需要确保不会增加i,直到它与下一个元素i+1不匹配。

    i = 0;
    while (i < n)
    {
        int j = i+1;
        if(arr[i] == arr[j])
        {
            for(int k = i; k<n; k++)
            {
                arr[k] = arr[k+1];
            }
            n--;
        }
        else
        {
            i++;
        }
    }
    

答案 1 :(得分:0)

使用std::unique

auto end = std::unique(std::begin(arr), std::end(arr));

答案 2 :(得分:0)

for(int i=0; i < count(original_array); i++)
{
    if(i == 0) // check for first entry
    {
        new_array[] = original_array[i];
        temp = original_array[i];
    }
    if(temp != original_array[i]) // check thereafter
    {
        new_array[] = original_array[i];
        temp = original_array[i];
    }
}