【问题标题】:How many this word in the array string数组字符串中有多少这个词
【发布时间】:2021-12-04 22:11:30
【问题描述】:

我想计算字符串中有多少这个词和运算符,但我尝试使用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] != '\0'; 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 函数放在它上面时它不起作用。请告诉我如何解决这个问题,如果我需要编写更多函数来查找。

【问题讨论】:

  • 始终,始终首先阅读文档:man strchr
  • 顺便说一句。您用strstr 标记了您的问题,但您没有使用它,而是使用了“完全”不同的东西。

标签: arrays c string loops strstr


【解决方案1】:

strchr(cpysin, 'SIN') 错误。

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

请记住,在 C 语言中,您使用单个字符 'a' 或字符串 "cos"(或者您可以遇到宽字符/字符串)

使用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 '\0' which is at the end of buff
//there is serious problem if we read past it
while(*ptr != '\0')
{
    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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 2013-02-13
    • 1970-01-01
    相关资源
    最近更新 更多