檢查給定字串是否為C語言關鍵字的程式
關鍵字是在C++庫中預定義或保留的詞,具有固定的含義,用於執行內部操作。C++語言支援60多個關鍵字。
所有關鍵字都小寫,例如auto、break、case、const、continue、int等。
C++語言中32個關鍵字也存在於C語言中。
| 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 | volatile |
| do | if | static | while |
以下30個保留字在C語言中不存在,而是C++語言新增的:
| asm | dynamic_cast | namespace | reinterpret_cast |
| bool | explicit | new | static_cast |
| catch | false | operator | template |
| class | friend | private | this |
| const_cast | inline | public | throw |
| delete | mutable | protected | true |
| try | typeid | typename | using |
| using | using | wchar_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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP