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


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

所有关键字都小写,例如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);
}

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

which is a keyword

更新于:2019年10月7日

12K+ 次浏览

开启你的职业生涯

完成课程并获得认证

开始学习
广告