//count times of specific charecter in c-string; #include <iostream> int count_char(const char * str, char ch ); int main() { using namespace std; //char * string = "hello world!"; char string[] = "hello world!"; char ch; int count; cout << "Please enter the character you want to count:\n"; cin >> ch; count = count_char(string, ch); cout << string << " contains " << count << " " << ch << endl; cin.get(); cin.get(); return 0; } int count_char( const char * str, char ch ) // 改进1:const { unsigned int count = 0; char a = ch; while( *str != '\0' ) //空值字符的数字编码=0,所以也可以改写为:while( *str ),这样的写法好像可读性不是很好 { if ( *str == ch) count++; str++; } return count; }