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

码:

#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;
}


程序输出与上面显示的相同。

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

10-12 02:16