用C程序检查给定的字符串是否为关键字?

关键字是预定义或保留的单词,在C ++库中可用,具有固定的含义,并且用于执行内部操作。C ++语言支持64个以上的关键字。

每个关键字都以小写字母形式存在,例如auto,break,case,const,continue,int等。

C ++语言中的32个关键字,也可用C语言提供。

autodoubleintstruct
breakelselongswitch
caseenumregistertypedef
charexternreturnunion
constfloatshortunsigned
continueforsignedvoid
defaultgotosizeofvolatile
doifstaticwhile

这是30个不在C中但已添加到C ++中的保留字

asmdynamic_castnamespacereinterpret_cast
boolexplicitnewstatic_cast
catchfalseoperatortemplate
classfriendprivatethis
const_castinlinepublicthrow
deletemutableprotectedtrue
trytypeidtypenameusing
usingusingwchar_t
Input: str="for"
Output: for is a keyword

说明

  • 关键字是保留字,不能在程序中用作变量名。

  • C编程语言中有32个关键字。

将字符串与每个关键字进行比较(如果字符串相同,则字符串为关键字)

示例

#include <stdio.h>
#include <string.h>
int main() {
   char keyword[32][10]={
      "auto","double","int","struct","break","else","long",
      "switch","case","enum","register","typedef","char",
      "extern","return","union","const","float","short",
      "unsigned","continue","for","signed","void","default",
      "goto","sizeof","voltile","do","if","static","while"
   } ;
   char str[]="which";
   int flag=0,i;
   for(i = 0; i < 32; i++) {
      if(strcmp(str,keyword[i])==0) {
         flag=1;
      }
   }
   if(flag==1)
      printf("%s is a keyword",str);
   else
      printf("%s is not a keyword",str);
}

输出结果

which is a keyword