ch6字串
ch6 字串處理
6-1 C語言字串的組成元素--字元
C語言中字元相當於是常數,每個字元都有其對應的數值,此對應表稱為ASCII(http://zh.wikipedia.org/wiki/ASCII)表,例如:A相當於65。宣告時char表示字元資料型別,以單引號括起來。
char ch = 'A‘;
在C 語言中並沒有字串的資料型別,需宣告為『字元陣列』。字串為字元組成,且會在字串最後加上’\0’ 表示字串結束。
宣告格式:
char 字元陣列名稱[字串長度];
char name[10]=“Tony”;
name[]陣列長度為5,而非4。
C語言字元函式庫
請參閱c++ reference http://www.cplusplus.com/reference/
程式中需包含「include <cctype>」或include <ctype.h>,成功回傳1,失敗回傳0
isprint(char) - 是否為可列印字元(ASCII碼 32~126),ASCII碼32為space
isgraph(char)- 是否為可顯示字元(ASCII碼 33~126)
isalnum(char) - 是否為英文字母或數字字元(A~Z, a~z, 0~9)
isalpha(char) - 是否為英文字母(A~Z, a~z)
isdigit(char) - 是否為數字字元(0~9)
isxdigit(char) - 是否為16進位數字字元(0~9, A~F)
islower(char) - 是否為小寫英文字母(a~z)
isupper(char) - 是否為大寫英文字母(A~Z)
isspace(char) - 是否為空白字元(ASCII碼 32)
ispunct(char) - 是否為標點符號字元,為print字元但不包含space、letter與數字
iscntrl(char) - 是否為控制字元,(ASCII碼0-31)、與DEL(0x7F)
tolower(char) - 轉成小寫英文字母
toupper(char) - 轉成大寫英文字
字串範例—字串轉成小寫
請寫一程式,將字串”Good Morning”轉成小寫
C語言練習題—小寫轉成大寫,大寫轉成小寫
請寫一程式,將字串”Good Morning”中小寫轉成大寫,大寫轉成小寫。可使用islower(),isupper(),tolower(),toupper()等函式。
提示:
if (islower(str[i])){
str[i]是小寫字元,執行此敘述
}else{
str[i]不是小寫字元,執行此敘述
}
6-2 C語言字串函式庫
程式需要包含「include <cstring>」或「include <string.h>」,函式功能請參閱http://www.cplusplus.com/reference/cstring/
int strcmp(const char *string1,const char *string2),比較string1與string2相等回傳0
int strlen(const char *string) ,回傳string的長度
char * strcpy ( char * destination, const char * source ); 將source所指字串複製到destination所指字串中
char * strcat ( char * destination, const char * source ); 將source所指字串接到destination所指字串的後面
char *strtok(char *string1, const char *string2),將string1所指字串使用string2所指分隔字元,切成幾個字串。
strcmp(const char *string1,const char *string2)
strcmp程式範例
char * strcpy ( char * destination, const char * source );
strcpy程式範例
char * strcat ( char * destination, const char * source );
strcat程式範例
char *strtok(char *string1, const char *string2)
語法:int strtok (string str1, string str2)
說明: 將字串str1 依字串str2 的值切開成小段小段的字串。
strtok程式範例
6-3 C++語言string物件
程式需要包含「include <string>」,函式功能請參閱http://www.cplusplus.com/reference/string/string/
6-4 字串解題範例
C++字串範例.a009-解碼器 acm-uva458