计算仅包含元音的子串的数量

标签 c string algorithm substring c-strings

我编写了一段代码来查找给定子字符串的元音子字符串。但我需要帮助来计算由此形成的子字符串?

代码:

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool isVowel(char c) {
    return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}

void substr(char str[], int low, int high)
{
    printf("%.*s \n\n", high-low+1, (str+low));
}

int main(int argc, const char *argv[]) {

    char str[] = "aeixae";

    int length = strlen(str);

    int start_index = 0, end_index = 0;

    for (int x=0; x<=length; x++) {
        if (x == length || !isVowel(str[x])) {
            end_index = x;
            substr(str, start_index, end_index - 1 );
            start_index = end_index + 1;
        }

    }
    return 0;
} 

最佳答案

给你。

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool isVowel( char  c) 
{
    const char *vowels = "aeiou";

    return strchr( vowels, c ) != NULL;
}

void output_substring( const char *s, int n )
{
    printf( "%*.*s\n", n, n, s );
}

int main(void) 
{
    char s[] = "aeixae";
    size_t count = 0;

    for ( const char *p = s; *p != '\0'; )
    {
        while ( *p != '\0' && !isVowel( *p ) ) ++p;

        if ( *p != '\0' )
        {
            ++count;
            const char *q = p;

            while ( *p != '\0' && isVowel( *p ) ) ++p;

            output_substring( q, p - q );
        }
    }

    printf( "There are %zu substrings\n", count );

    return 0;
}

程序输出为

aei
ae
There are 2 substrings

另一种方法是使用标准 C 函数 strcspnstrspn 而不是 while ;循环。

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

void output_substring( const char *s, int n )
{
    printf( "%*.*s\n", n, n, s );
}

int main(void) 
{
    char s[] = "aeixae";
    size_t count = 0;
    const char *vowels = "aeiou";

    for ( const char *p = s; *p != '\0'; )
    {
        p += strcspn( p, vowels );

        if ( *p != '\0' )
        {
            ++count;
            const char *q = p;

            p += strspn( p, vowels );

            output_substring( q, p - q );
        }
    }

    printf( "There are %zu substrings\n", count );

    return 0;
}

程序输出与上图相同。

关于计算仅包含元音的子串的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60111564/

相关文章:

c - 是否可以从 C 访问程序集中定义的变量?

swift - 找到一个字符串并提取后面的字符

c++ - 创建一个基于字符串的Class数组

C - 读取未知长度的字符串说明

c - 使用指针的快速排序和冒泡排序,将这两个实现到 calc.c 中

c - 为什么在下面的编程中结构显示的内存比实际内存少

python - 给出错误答案的最小硬币变化类

java - 无向图DFS的并行实现

c - Seg Fault,可能的数组指针问题(Radix Sort Implementation)

c - 为什么在 C 中调用函数时要指定函数的返回类型?