【问题标题】:Counting substrings in a string计算字符串中的子字符串
【发布时间】:2023-03-28 12:00:01
【问题描述】:

我的任务是编写一个带有指针的小程序,我遇到了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,因为子字符串 'cu' 在 'cucumber' 中出现了 2 次 - 然而,我的编译器告诉我我正在使用字符,而我应该使用常量字符。除了,我不知道该怎么做。

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

【问题讨论】:

  • 执行这个程序(如果它可以编译)将导致未定义的行为,因为设置 ptr[x] 将尝试写入 ptr 数组,但是,ptr 被声明为单个指针,而不是数组。
  • 老兄,您正在写入未分配的内存。您还没有为 char** ptr 分配内存;
  • 作业又出问题了!!
  • @siu 还有?提出问题的上下文与 Stack Overflow 无关。我们只关心问题的格式和清晰程度。在这种情况下,很清楚任务是什么,问题是什么,并且发布了迄今为止的工作。所以这是一个相当不错的问题。它只是需要更少的表情符号。

标签: c string count


【解决方案1】:
// 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);
}

【讨论】:

  • 这段代码效率很低。所有这些对 strlen 的重复调用都是不必要的。
  • 感谢您的努力 =) 我仍然难以理解:strlength 的相关性如何,此外:testStr 的 strlen 不会总是高于 findStr 吗? for 循环不会结束,对吗?
  • 另外,我的编译器说“[Error] 'for' 循环初始声明只允许在 C99 模式下”
【解决方案2】:

分配内存用于存储指针值

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

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2017-10-20
    • 2019-09-14
    • 1970-01-01
    相关资源
    最近更新 更多