More Related Content
More from requiemformemories
More from requiemformemories (13)
Ch4 字元陣列
- 3. char 的宣告與初始化
• 沒錯! char 正是個字元喔!
• 宣告方式像這樣: char name;
• 如果要初始化的話: char name='a';
• 有沒有非常簡單呢?
- 4. char 陣列!
★這樣一個 char 只能存一個字母好不方便…
…
不如來宣告個 char 陣列吧!
★形式如下: char name[10];
• 如果要初始化的話: char
name[10]="Ted";
- 7. 神秘的 ascii 碼
• C++ 中字元相當於是常數,每個字都有其
對應的數值,此對應表稱為 ASCII 表,例
如: A 相當於 65 。
那其他的字元的常數是什麼呢?
讓我們來看看 ascii 碼表!
- 9. ctype 好朋友們
★使用前引入標頭檔 <cctype> ( 是回傳 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)
- 11. cstring 好朋友們
★使用前引入標頭檔 <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 所指分隔字元,切成幾個字串
。
- 14. isalnum(char) 示範- 印出哪些是英文字母或數字
★code 如下:
執行結果
#include<iostream>
#include<cctype>
using namespace std;
int main(){
char a[]="zsisc*20";
int i=0;
while(a[i]!='0'){
if(isalnum(a[i]))
cout<<" 第 "<<i+1<<" 項是英文字母或數
字 "<<endl;
i++;
}
}
- 16. strcmp 示範
- 比較兩字串相不相等
★code 如下:
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char s1[]="FumiTsuki";
char s2[]="fumitsuki";
if (!strcmp(s1,s2))
cout << "s1 等於 s2" <<endl;
else
cout << "s1 不等於 s2"
<<endl;
}
執行結果
- 17. strcpy 示範 複製字串至另一個字串
★code 如下:
#include <iostream>
#include <cstring>
using namespace std;
執行結果
int main(){
char s1[]="Fumitsuki";
char s2[]="EightPlates";
cout<<" 原來字串 s1 為 "<<s1<<endl;
strcpy(s1,s2);
cout << " 複製後字串 s1 為 "
<<s1<<endl;
}
- 18. strcat 示範
- 複製字串至另一個字串
★code 如下:
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char s1[]="Fumi";
char s2[]="Tsuki";
cout << " 原來字串 s1 為 " <<
s1<<endl;
strcat(s1,s2);
cout << " 串接後字串 s1 為 " <<
s1<<endl;
}
執行結果
- 19. strtok 示範
★code 如下:
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char s1[]="fumi tsuki";
char s2[]=" ";
strtok(s1,s2);
cout<<" 切除後的結果
是 :"<<s1<<endl;
}
- 字串以空白切開
執行結果
- 20. strlen 示範
- 計算字串長度
★code 如下:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char a[]="helloC++";
cout<<" 此字串長度
是 "<<strlen(a)<<endl;
}
執行結果