檢查給定字串是否為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);
}

輸出

which is a keyword

更新於:2019年10月7日

12K+ 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

開始學習
廣告
© . All rights reserved.