首页 > 解决方案 > 如何删除“继续;”?

问题描述

我有这个 C++ 程序,它试图从 char 数组中删除元音。这可行,但我想在没有continue;.

#include <iostream>
#include <string.h>
using namespace std;


int main() {


    char s[21],afterElimination[19],vowels[] = "aeiou";
    cin.get(s,20);
    int i, n = strlen(s),VowelPos = -1,h = 0;
    for (i = 0; i < n; i++) {
        if (strchr(vowels,s[i])) {
            if(VowelPos == -1) {
                VowelPos = i;
                continue;
            } 
            VowelPos = i - 1;
        }
        afterElimination[h++] = s[i];

    }
    afterElimination[h] = NULL;
    strcpy(afterElimination + VowelPos, afterElimination + VowelPos + 1);

    cout<<afterElimination;


    return 0;
}

标签: c++continue

解决方案


continue从循环中删除非常容易。您需要的是循环中的两个索引。一个用于源数组中的位置,另一个用于要复制到的数组中的位置。然后将复制操作放在 if 语句中,因此如果没有复制,则无需执行任何操作以进行下一次迭代。那会让你循环看起来像

for (int source_index = 0, copy_index = 0; source_index < n; ++source_index) { // increment source_index always
    if (!strchr(vowels,s[i])) {
        // this isn't a vowel so copy and increment copy_index
        afterElimination[copy_index++] = s[i];
    }
    // now this is the continue but we don't need to say it
}

推荐阅读