从单词c 的顺序消除元音

Eliminating Vowels in order from a word C++

本文关键字:顺序 单词      更新时间:2023-10-16

首次在stackoverflow上。在研究和编码我在编程中的期末考试时,我发现了一个我可以在精神上解决的问题,但是当我尝试将其放入C 时,它实际上并不奏效。

所以问题是我的母语,罗马尼亚语,但我将尝试翻译它。因此,问题要我要从键盘上阅读一个单词,然后在屏幕上显示它,每次消除元音。例如,如果我在程序中输入"编程"一词,则应显示:

  1. progrmming-消除
  2. 编程 - 消除E
  3. programmng-消除i
  4. prgramming-消除o
  5. 编程 - 消除u

我的代码看起来像这样:

#include <iostream>
#include <string.h>
using namespace std;
int main()
{
    char v[6]="aeiou",s1[21],s2[21];
    int i,j;
    cin.get(s1,20);
    for(i=0;i<strlen(v);i++)
    {
        strcpy(s2,s1);
        j=0;
        while(j<strlen(s2))
        {
            if(strchr(v[i],s2[j])!='')
                strcpy(s2+j,s2+j+1);
            else
                j++;
        }
        cout<<s2<<endl;
    }
    return 0;

我在"如果"语句上有一个错误,但我似乎找不到解决方案。在从" V [i]"中删除" [i]"之后,它起作用,但是我只需要一次消除一个元音,而不是全部。希望有人可以在这里帮助我。谢谢!

编辑:解决的问题,我将在这里让我的代码,因为问题是从罗马尼亚学士学位的主题

中获取的
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
    char v[6]="aeiou",s1[21],s2[21];
    int i,j,x;
    cin.get(s1,20);
    for(i=0;i<strlen(v);i++)
    {
        strcpy(s2,s1);
        j=0;
        while(j<strlen(s2))
        {
            if(s2[j]==v[i])
                strcpy(s2+j,s2+j+1);
            else
                j++;
        }
        cout<<endl;
        cout<<s2<<endl;
    }
    return 0;
}

很抱歉误解,但是在这里,我们没有教会使用诸如std::string::find_first_of之类的东西,只是strcmpstchr之类的基本功能。

好吧,您的大错误是您在迭代之前在元音上迭代。

您应该迭代输入字符串,对于每个字符,请检查它是否是元音。您可以通过使用v使用strchr检查char是否是元音。

对于字符串中的每个字符,您有两种情况:

  1. 角色是元音
  2. 字符不是元音

在第一种情况下,您应该从字符串中删除该字符,这意味着移动字符串的其余内容。

例如,如果您的字符串为编程,然后跳入了第一个 o ,则必须将其余的 Gramming 移动到左:

0 1 2 3 4 5 6 7 8 9 10
p r o g r a m m i n g
p r   g r a m m i n g
p r g r a m m i n g

在第二种情况下什么都没有发生(除非您将字符串char复制到char char chor char char char ch)。

查看以下解决方案,它使用[memmove][1]将字符串向左移动,但也可以使用简单的环路来完成。阅读,研究并理解它。如果您需要更多帮助,请毫不犹豫地问。

void incremental_vowel_removal(const char *instr) {
  // the vowels
  static const char *vowels = "aeiou";
  // length of the input string
  int len = strlen(instr);
  // I will work on a copy of the string because it is easier
  char *ostr = (char*)malloc((len+1) * sizeof(char));
  strcpy(ostr, instr);
  // for each char in the string
  for (int i = 0; i < len; ++i) {
    // if it is a vowel
    if (strchr(vowels, ostr[i])) {
      // shift remaining string to the left
      // this will erase the currect character from the string
      memmove(ostr+i, ostr+i+1, len-i);
      // print this partial result
      printf("%sn", ostr);
      // the length is decreased by one, so let's reflect it
      len -= 1;
    }
  }
  // free the allocated memory
  free(ostr);
} 

更新:我用calloc替换CC_7,因为无需零启动字符串,因为strcpy之后被调用。