W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
下面程序計算字符串中字母‘a(chǎn)’出現(xiàn)的次數(shù):
apstring fruit = "banana";
int length = fruit.length();
int count = 0;
int index = 0;
while (index < length) {
if (fruit[index] == ’a’) {
count = count + 1;
}
index = index + 1;
}
cout << count << endl;
這個程序展示了一個叫做“計數(shù)器”的習(xí)慣用法。變量count初始化為0,每次找到一個‘a(chǎn)’時加1。退出循環(huán)時,count就是結(jié)果,即字符串中‘a(chǎn)’的個數(shù)。
作為練習(xí),請將該代碼封裝到一個名為countLetters的函數(shù)中,該函數(shù)要以字符串和字母作為參數(shù)。
第二個練習(xí),請重寫該函數(shù),要求該函數(shù)不能遍歷字符串,而是使用我們前一節(jié)編寫的find版本。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: