我們已經(jīng)知道,用strlen ()函數(shù)可以得到字符串的長(zhǎng)度。下面用到了strlen ()函數(shù),這是
一個(gè)可以縮短字符串長(zhǎng)度的程序:
#include#includevoid fit (char *,unsigned int);
int main(void )
{
char mesg[] = "Hold on to your hats,hackers.";
puts(mesg);
fit(mesg,7);
puts(mesg);
puts("Let's look at some more of the string.");
puts(mesg + 8);
return 0;
}
void fit (char *string,unsigned int size)
{
if(strlen(string) >size)
*(string+size) = '\0';
}
輸出結(jié)果如下:
Hold on to your hats,hackers.
Hold on
Let's look at some more of the string.
to your hats,hackers.
fit函數(shù)是在指定位置放下一個(gè)空字符,使得puts()顯示時(shí)遇到那個(gè)空字符就停止了。
2.strcat()strcat(代表string concatenation)函數(shù)接受兩個(gè)字符串參數(shù)。它將第二個(gè)字符串的拷貝添加到第一個(gè)字符串的末尾,從而使得第一個(gè)字符串組合形成一個(gè)新的字符串,但是第二個(gè)字符串并沒(méi)有被改變。
下面程序展示了該函數(shù)的功能
#include#include#define SIZE 80
int main(void )
{
char flower[SIZE];
char addon[] = "s smell like good.";
puts("what is your favorite flower?");
gets(flower);
strcat(flower,addon);
puts(flower);
puts(addon);
return 0;
}
結(jié)果如下:
what is your favorite flower?
Rose
Roses smell like good.
s smell like good.
strcat函數(shù)并沒(méi)有考慮第一個(gè)字符串所在數(shù)組是否能容納下第二個(gè)字符串,容易使得多出來(lái)的字符串溢出到其它內(nèi)存空間,這時(shí)候要么做個(gè)長(zhǎng)度檢查工作,要么可以使用strncat函數(shù),設(shè)置第三個(gè)參數(shù),指明最多能添加的字符數(shù),如strncat(flowers,addon,13);那么就會(huì)加到addon第十三個(gè)字符或遇到空字符為止。
3.strcmp()
strcamp(代表string comparison)是對(duì)字符串內(nèi)容進(jìn)行比較的函數(shù)。
#include#include#define ANSWER "keep"
#define MAX 40
int main(void )
{
char t[MAX];
puts("What is your need?");
gets(t);
while(strcmp(t,ANSWER))
{
puts("No,that's wrong, Try again.");
gets(t);
}
puts("That's right!");
return 0;
}
結(jié)果如下
What is your need?
money
No,that's wrong, Try again.
courage
No,that's wrong, Try again.
keep
That's right!
strncmp是其變種函數(shù),多了第三個(gè)參數(shù)指定比較到第幾位字符數(shù),可以用來(lái)比較前面部分相同的字符串。
4.strcpy()
一般直接給指向字符串的指針賦值,都是復(fù)制字符串的地址,而不是本身。這時(shí)候就可以用strcpy
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機(jī)房具備T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級(jí)服務(wù)器適合批量采購(gòu),新人活動(dòng)首月15元起,快前往官網(wǎng)查看詳情吧
分享題目:C語(yǔ)言學(xué)習(xí)筆記(7)——字符串函數(shù)-創(chuàng)新互聯(lián)
網(wǎng)頁(yè)地址:http://sd-ha.com/article12/deipgc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站內(nèi)鏈、微信公眾號(hào)、網(wǎng)站制作、網(wǎng)頁(yè)設(shè)計(jì)公司、服務(wù)器托管、微信小程序
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容