我想計算字串中這個單詞和運算子的數量,但我嘗試使用但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);
}
我只在回圈中進行 while 以查找其中有多少 sin 時才作業,但是當我在其上放置 cos 函式時它不起作用。請告訴我如何解決這個問題以及如果我需要撰寫更多函式來查找怎么辦。
uj5u.com熱心網友回復:
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321529.html
