计算字符串中的子字符串

时间:2014-11-20 14:32:50

标签: c string count

我的任务是使用指针创建一个小程序,我遇到const char*s的问题。该程序用于计算子字符串在主字符串中出现的次数。此外,子字符串开始的不同位置应保存在char ** ptr中。这是我的小测试代码:

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

main()
{
    int i=-1;
    int k=0;
    char** ptr;
    char* str="cucumber";
    char* substr="cu";

    while(strstr(str, substr)!=NULL)
        {
            i++;
            ptr[i]=strstr(str, substr);
            str = strpbrk(str, substr)+1;
            k++;
        }

    printf("%i",k);
}

它应该打印2,因为子串&#39; cu&#39;在黄瓜中出现2次&#39; - 然而,我的编译器告诉我,我正在使用字符,当我应该使用常量字符时。除此之外,我不知道该怎么做。

strstr()函数需要它们。我应该改变什么?

2 个答案:

答案 0 :(得分:0)

// note:
// 1) correction to declaration of main()
// 2) addition of return statement
// 3) 'substr' is a poor name choice for a variable, as 
//    a) it looks like a C lib function (it is a ACL library function)
//    b) it does not clearly convey what the variable contains
// 4) clutter in the 'while' loop removed
// 5) 'while' loop is replaced by a 'for' loop so more can be accomplished with less code 
// 6) unneeded variables are eliminated
// 7) the 'for' loop stops when there is no possibility of further testStr occurrences
// 8) the printf() clearly indicates what is being printed



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

int main()
{

    char* testStr="cucumber";
    char* findStr="cu";
    int k = 0;

    for( int i=0; strlen(&testStr[i]) >= strlen(findStr); i++)
    {
        if( strstr(&testStr[i], findStr) != NULL)
        {
            k++;
        }
    }
    printf("\nnumber of occurrences of %s in %s is %d\n", findStr, testStr, k);

    return(0);
}

答案 1 :(得分:0)

分配用于存储指针值的内存

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

#define MAX_SUB_STR 10
int main()
{
    int i;
    int k;
    char* ptr[MAX_SUB_STR];
    char* str="cucumber";
    char* temp;
    char* substr="cu";

    i = 0;
    k = 0;
    temp = str;
    while(strstr(temp, substr)!=NULL && k < MAX_SUB_STR)
        {
            ptr[k]=strstr(temp, substr);
            temp = ptr[k] + strlen(substr);
            k++;
        }

    printf("%i\n",k);
    for (i = 0; i < k; i++)
        printf("%p\n",ptr[i]);
    return 0;
}