簡體   English   中英

C ++ Char Array刪除重復的字符

[英]C++ Char Array deleting repeated characters

嗨,我只是在尋求幫助,我編寫了一段簡短的代碼來接收字符數組,然后將通過一個函數來運行該函數,該函數將刪除所有重復的字符,我有一個小錯誤,因為它沒有刪除此處的最后一個重復的字母是代碼,我也會在代碼之后輸入輸出。

#include <iostream>

#include <fstream>

#include <ostream>

using namespace std;

const int max_num_chars=10;

void deleteRepeats(char c[], int& size);


int main()
{
    char c[]={'a','b','b','b'};
    int c_size=4;

    cout<<"This Program reads characters into a partially filled array and then delete's repeats! \n";
    cout<<"Here is the original array \n";
    for (int i=0;i<c_size;i++)
    {
        cout<<c[i]<<"\n";
    }
    deleteRepeats(c, c_size);
    cout<<"Here is the array after the deleteRepeats function! \n";
    for (int i=0;i<c_size;i++)
    {
        cout<<c[i]<<"\n";
    }
    system("pause");
    return 0;
}
void deleteRepeats(char c[],int& size)
{
    int num = size;
    int start = 0;

    while(start != num)
    {
        char test = c[start];
        for(int i = start+1; i <= num;i++)
        {
            if(test==c[i])
            {
                for(int j = i;j<num;j++)
                    {
                    c[j] = c[j+1];
                    }
                num-=1;
            }
        }
    start +=1;
    }
    size = num;
}

輸出為...該程序將字符讀入部分填充的數組,然后刪除重復項! 這是原始數組abbb這是deleteRepeats函數之后的數組! abb按任意鍵繼續。

抱歉,我只是通過添加以下代碼自己弄清楚了這一點,從而解決了問題

for(int j = i;j<num;j++)
                    {
                    c[j] = c[j+1];
                    }
                num-=1;
                start-=1; 

盡管對此有更好的算法。 就您而言:

在函數“ deleteRepeats”內部,在循環“ for(int i = start + 1; i <= num; i ++)”內部

當您刪除下一個相同元素時,您在增加“ i”而沒有考慮到現在在同一“ i”處,刪除后也可能存在重復元素。

解決方案:刪除元素后,還要減小i的值。 所以現在你的循環看起來像這樣

for(int i = start+1; i <= num;i++)
    {
        if(test==c[i])
        {
            for(int j = i;j<num;j++)
                {
                c[j] = c[j+1];
                }
            num-=1;
          // correction
            i--;
          // correction
        }
    }

如果您有任何問題的理解,請回復...

為什么只需要一個嵌套循環就有兩個?

void deleteRepeats(char c[], int& size) {
    // Trivial case of empty array: do nothing.
    if(size <= 0) // Why is `size` a signed `int` and not `size_t`?
        return;

    // First character is automatically not a repetition.
    // So for each character from the second onward,
    // move it if it is different from the previous character,
    // otherwise skip over it.
    char* read = c + 1;
    char* write = read;
    char* end = c + size;
    char prev = *c;
    while(read != end) {
        if(*read != prev) {
            prev = *read;
            *write++ = prev;
        }
        ++read;
    }

    // Finish up.
    size = write - c;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM