1、c类型的字符串和数组字符串
unsigned int c_in_str(const char *str,char ch){
unsigned int count = 0;
while(*str){
if(*str == ch)
count++;
str++;
}
return count;
}
using namespace std;
int main(){
char mmm[15] = "minimum";
char *wail = "ululate";
cout << c_in_str(mmm,'m') << endl;
cout << c_in_str(wail,'u') << endl;
return 0;
}
使用指针表示法提醒注意,参数不一定必须是数组名,也可以是其他形式的指针。str最初指向字符串的第一个字符,因此*str表示的是第一个字符。例如,第一次调用该函数后,*str的值将为m——“minimum”的第一个字符。只要字符不为空值字符(\0),*str就为非零值,因此循环将继续。在每轮循环的结尾处,表达式str++将指针增加一个字节,使之指向字符串中的下一个字符。最终,str将指向结尾的空值字符,使得*str等于0——空值字符的数字编码,从而结束循环。
2、string字符串当做参数,string对象与结构相似。
void display(const string sa[],int n){
for(int i=0;i<n;i++)
cout << i+1 <<": "<<sa[i]<<endl;
}
int main(){
string list[3];
list[0] = "aaaa";
list[1] = "bbbb";
list[2] = "cccc";
display(list,3);
return 0;
}