排序2个char数组

时间:2016-11-13 15:58:52

标签: c++ arrays sorting char

我正在努力完成我的课程的作业,我们必须将用户的输入转换为字符数组(单词)并在需要时取出输入单词中的重复项。将修改后的数组(word)的数组与字母数组(abc)进行比较,以从列表中删除重复的字母。删除重复项后,只需输出修改后的单词,然后将新形式的字母输出到newAbc数组中。

例如:

HELLO这个词首先成为HELO,然后在与字母表比较后,新数组的结束输出应为HELOABCDFGIJKMNPQRSTUVXYZ。

我更多地依赖for循环将新单词与字母表进行比较。

    char word[20], newAbc[40] = { '\0' }; 
    char abc[27] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; 
    int i = 0, b = 1, n = 0, leng, dup; 
    //dup counts up the repeats but is established in the first portion of the program but i've excluded it as it works perfectly.

    cout << "Please enter a word: "; 
    cin >> word; 

    leng = strlen(word); 

    b = 0; 
    n = leng - dup; 
    i = 0; 

    for (i = 0; i < n; i++) 
    { 
        for (b = 0; b < 27; b++) 
        { 
            if (newAbc[i] != abc[b]) 
            { 
                newAbc[n] = abc[b]; 
                n++; 
            } 
        } 
    } 

    for (i = 0; i < 27; i++) 
        cout << newAbc[i]; 
    cout << endl; 

    return 0; 
} 

我很欣赏对我的错误的任何见解。

1 个答案:

答案 0 :(得分:0)

崩溃的主要问题是您正在更改n内部for循环以便在newAbc中进行迭代。并且你的if条件将至少为25次,因此在每次迭代中将n递增25(最小值),从而导致访问超出范围的内存(SEG-FAULT)。

for (i = 0; i < n; i++) 
    { 
        for (b = 0; b < 27; b++) 
        { 
            if (newAbc[i] != abc[b]) // this condition is not correct
            { // this will be true atleast 25 times
                newAbc[n] = abc[b]; // wrong memory access
                n++; // here is the problem
            } 
        } 
    } 

假设您的重复计数工作正常,以下是所需的更改: -

    char word[20];

    // FIXME: your new array should not contain no duplicate so size can be 27
    char newAbc[40] = {'\0'}; 

    // FIXME: simply can be char abc[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char abc[27] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; 

    cout << "Please enter a word: "; 
    cin >> word; 

    // dup counts up the repeats but is established in the first portion of 
    // the program but i've excluded it as it works perfectly.

    // Lets say word = "HELLO"; so dup = 1, and newArray, should have "HELO"
    memcpy(newAbc, "HELO", 4); // from your excluded part of code
    int dup = 1; // from your excluded part of code

    int leng = strlen(word); // length of input word
    int n = leng - dup; // char remained to be inserted

    // iterator for new array(newAbc)
    int c = n; // n elements are already there

    // Just reversed your loop
    for (int b = 0; b < 27; b++) 
    {
        int found = 0;
        for (int i = 0; i < n; i++) 
        { 
            if (newAbc[i] == abc[b]) 
            { 
                found = 1;
                break;
            } 
        } 

        if (!found)
        {
            newAbc[c] = abc[b]; 
            c++; 
        }
    }

    for (int i = 0; i < 27; i++) 
        cout << newAbc[i]; 
    cout << endl; 

    return 0;