c - 在 C 中使用指针从字符串中删除元音

标签 c pointers

我正在尝试使用指针从一串二维数组中删除元音。我能够通过元音的 ASCII 值检测到元音,但字符串没有得到更新。

这部分代码不能更改。

void remove_vowel(char strings[NUM_STRINGS][STRING_LENGTH])

我的代码哪里出错了?

更新后的代码:

void remove_vowel(char strings[NUM_STRINGS][STRING_LENGTH])
    {
        // loop through each row, starting intitally points to last element
        for (char(*p)[STRING_LENGTH] = strings; p != strings + NUM_STRINGS; ++p) {
            // variable q points to the first element       
            for (char *q = *p; q != *p + STRING_LENGTH; ++q) {

                if (*q != 'a' && *q != 'e' && *q != 'i' && *q != 'o' && *q != 'u') {
                    //printf("%c",*q);          
                    *q = *q;
                }
            }       
        }
    }

我能够使用下面列出的解决方案重写代码。感谢大家的帮助!

解决方案

void remove_vowel(char strings[NUM_STRINGS][STRING_LENGTH])
    {
        // store the array in a pointer
        char(*wordHolder)[STRING_LENGTH] = strings; 

        // loop through each row
        for (int i = 0; i < NUM_STRINGS; i++)
        {
            // assign worl
            char *letter = *wordHolder;
            char *dest = *wordHolder;

            // check if null character
            while (*letter != '\0') {
                // check for vowels
                if (*letter != 'a' && *letter != 'e' && *letter != 'i' && *letter != 'o' && *letter != 'u') {
                    // assign non-vowel letter to destination
                    *dest++ = *letter;
                } 
                // move to next letter
                letter++;

            }
            // add null pointer to end of destination
            *dest = '\0';

            // increment pointer position to next word
            wordHolder++;
        }
    }

最佳答案

让我们考虑一个等效的 C 语言。

在 C 语言中,您需要将文本视为数组。对于数组,当您删除一个插槽时,您需要移动剩余的项目以覆盖已删除的插槽。

让我们从这里开始。

void dont_copy_vowels(char text_array[STRING_LENGTH])
{
   char * p_source = &text_array[0];
    char * p_destination = &text_array[0];
    const unsigned int length = strlen(text_array);
    while (*p_source != '\0')
    {
      static const char vowels[] = "aeiou";
      if (strchr(vowels, *p_source) != NULL)
      {
        ++p_source;
        continue; // don't copy vowels.
      }
      // Copy the letter or symbol.
      *p_destination++ = *p_source++;
    }
    *p_destination = '\0';
}

由于您使用的是 C 风格字符串数组,因此您需要将上述代码放入一个循环中:

for (unsigned int string_index = 0;
     string_index < NUMBER_OF_STRINGS;
     ++string_index)
{
  dont_copy_vowels(strings[string_index]);
}

关于c - 在 C 中使用指针从字符串中删除元音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42206871/

相关文章:

c - 使用指针类型转换时值发生莫名其妙的变化

pointers - 何时使用 Box 而不是引用?

C指针不在同一个地址

C - 运行此应用程序时崩溃

c - 如何删除所有可能的二叉树节点?

c - 在 Lua 中与嵌套函数一起使用 C 变量

创建包含字符串的静态 C 结构

c - 如何提高 CMWX1ZZABZ-091 RTC(实时时钟)的精度

c - 获取 strtok 的最后一个标记

c - 如何在 C 中将 void 指针转换为结构?