字符串
字符串最適合放在char
類型數(shù)組中存儲(chǔ)。
例如要表示字符串"ABC"
宏所,數(shù)組元素必須按一下順序依次保存:
‘A’ 'B' 'C' '\0'
末尾null
字符\0
是字符串結(jié)束的"標(biāo)志"
printf("size %lu\n",sizeof("ABC")); //size 4
字符串字面量的中間可以有
null
字符肚邢,不過應(yīng)注意區(qū)分壹堰。字符串字面量"ABC"
是字符串,而字符串字面量"ABC\0CD"
不是字符串骡湖。
空字符串
char ns[] = ""; //元素個(gè)數(shù)是1贱纠,因?yàn)閮?nèi)部還有null字符
字符串的讀取
#include <stdio.h>
int main(void)
{
char name[100]; //為讀取的字符串附加null字符并存儲(chǔ)
printf("Please input your name: \n");
scanf("%s", name);//注意:scanf函數(shù)也不能加上& ! !
printf("Bonsvoir, Mr / Miss %s !! \n", name);
return 0;
}
字符串?dāng)?shù)組
#include <stdio.h>
int main(void)
{
char cs[][6] = {"Turbo", "NA", "DOHC"};
for (int i = 0; i < 3; i++) {
printf("cs[%d] = \"%s\"\n", i, cs[i]);
}
/*
cs[0] = "Turbo"
cs[1] = "NA"
cs[2] = "DOHC"
*/
return 0;
}
字符串處理
字符串長(zhǎng)度
/**
返回字符串長(zhǎng)度
@param s 字符串s
@return 字符串長(zhǎng)度
*/
int str_length(const char s[])
{
int len = 0;
while (s[len]) { //因?yàn)樽址詈笠粋€(gè)元素是\0
len++;
}
return len;
}
顯示字符串
/**
顯示字符串(打印字符串)
@param s 字符串s
*/
void put_string(const char s[])
{
int i = 0;
while (s[i]) {
putchar(s[i++]);
}
}
數(shù)字字符的出現(xiàn)次數(shù)
/**
數(shù)字字符的出現(xiàn)次數(shù)
@param s 需要計(jì)算的字符串
@param cnt 保存數(shù)字字符的數(shù)組
*/
void str_dcount(const char s[], int cnt[])
{
//將字符串s中的數(shù)字字符保存至數(shù)組cnt
int i = 0;
while (s[i]) {
if (s[i] >= '0' && s[i] <= '9') {
cnt[s[i] - '0']++;
}
i++;
}
}
英文字符的大小寫轉(zhuǎn)換
/**
將英文字符轉(zhuǎn)換為大寫字母
@param s 字符串
*/
void str_toupper(char s[])
{
int i = 0;
while (s[i]) {
s[i] = toupper(s[i]);
i++;
}
}
/**
將英文字符轉(zhuǎn)換為小寫字母
@param s 字符串
*/
void str_tolower(char s[])
{
int i = 0;
while (s[i]) {
s[i] = tolower(s[i]);
i++;
}
}
字符串?dāng)?shù)組的參數(shù)傳遞
/**
顯示字符串?dāng)?shù)組(字符串?dāng)?shù)組的參數(shù)傳遞)
@param s 字符串?dāng)?shù)組
@param n 數(shù)組元素?cái)?shù)量
*/
void put_strary(const char s[][6], int n)
{
for (int i = 0; i < n; i++) {
printf("s[%d] = \"%s\"\n", i, s[i]);
}
}
....
char cs[][6] = {"Turbo", "NA", "DOHC"};
put_strary(cs, 3);