数组字符串中有多少个这个词

How many this word in the array string

我想计算字符串中这个词和运算符的数量,但我尝试使用 strchr 但它不起作用。

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


int main()
{
    int x,count =0;
    char buff[100]="1+2.3(7^8)sin cos + cos sin_e-2x+x2*2!/_x1 sine";
    //gets(buff);
    strupr(buff);
    for (int i = 0; buff[i] != '[=10=]'; i++)
    {
        if (buff[i] == '+' || buff[i] == '-' || buff[i] == '*' ||
                buff[i] == '/' || buff[i] == '^'|| buff[i] == '(')
        {
            count++;
        }

    }
    char *op2;
    int check=0;
    char cpysin[100],cpycos[100];
    strcpy(cpysin,buff);
    strcpy(cpycos,buff);


    do
    {
        if(strchr(cpysin,'SIN')!=0)
        {
            count++;
            strcpy(cpysin,strstr(cpysin,"SIN"));
            cpysin[0] = ' ';
            cpysin[1] = ' ';
            cpysin[2] = ' ';
        }
        else
        {
            break;
        }
    }
    
    while(check==0);
    do
    {
        if(strchr(cpycos,'COS')!=0)
        {
            count++;
            strcpy(cpycos,strstr(cpycos,"COS"));
            cpycos[0] = ' ';
            cpycos[1] = ' ';
            cpycos[2] = ' ';
        }
        else
        {
            break;
        }
    }
    while(check==0);
    printf("FINAL \n%d",count);
}

我只在循环中执行此操作时才工作,同时试图找出其中有多少罪恶,但是当我在其上放置 cos 函数时它不起作用。请告诉我如何解决这个问题,如果我需要编写更多函数来查找怎么办。

strchr(cpysin, 'SIN')错了

不幸的是,编译器可能不会给您警告,因为 'SIN' 可以解释为 4 字节整数。第二个参数应该是一个整数,但是 strchr 真的想要字符,它把它砍掉到 'N'

请记住,在 C 中,您使用的是单个字符 'a' 或字符串 "cos"(或者您可以跨越 characters/strings)

使用strstr查找字符串。例如,要查找 "cos":

char* ptr = buff;
char* find = strstr(ptr, "cos");

"1+2.3(7^8)sin cos + cos sin_e-2x+x2*2!/_x1 sine";
---------------^ <- find

find 将指向 "cos + cos sin_e-2x+x2*2!/_x1 sine"

您可以递增 ptr 并查找下一次出现的 "cos"

另请注意,您可以声明 char buff[] = "...",而不必分配缓冲区大小。

char buff[] = "1+2.3(7^8)sin cos + cos sin_e-2x+x2*2!/_x1 sine";
int count = 0;
const char* ptr = buff;
const char* text = "cos";

//must terminate when ptr reaches '[=11=]' which is at the end of buff
//there is serious problem if we read past it
while(*ptr != '[=11=]')
{
    char* find = strstr(ptr, text);
    if (find != NULL)
    {
        printf("update [%s]\n", find);
        count++;
        ptr = find + strlen(text);
        //next search starts after
    }
    else
    {
        ptr++;
        //next character start at next character
    }
}
printf("%s count: %d\n", text, count);