一,函数篇 (比较简单,仅提两个问题而已)
问题一: 编写一个程序判定一个字符在一个字符串中出现的次数,如果该字符不出现则返回值 0。
问题二: 编写一个程序判定一个子串在一个字符串中出现的次数,如果该子串不出现则返回值0。
//答案如下:
// 题一:
#include <iostream> #include <string> #include <cstdlib> using namespace std;
int char_count(string s, char letter) { int count = 0; int length = s.length(); int i = 0; while(i<length) { char temp = s.at(i); if(temp == letter) count++; i++; } return count; }
int main() { string str; char c; cout<<"Enter a string."; getline(cin, str); cout<<"Enter a character."; cin.get(c); cout<<"This characater appears "<<char_count(str, c)<<" times"<<endl; system("pause"); return 0; }
// 注意,这个程序如果通过VC编译会有问题,这是VC的BUG。建议大家用DEV 编译。
// Dev 下载网址:
http://prdownloads.sourceforge.net/dev-cpp/devcpp4990setup.exe
// 题2:
#include <iostream> #include <cstdio> //#include <string> #include <cstdlib> using namespace std;
int str_count(char *substr, char *str) { char * substring, * string; int count = 0; while(*str) { for(string = str++, substring = substr; *string == *substring; string++, substring++) { if(!*(substring+1)) { ++count; } } } return count; }
int main() { char str[100], substr[20]; cout<<"Enter a string:"; cin.getline(str, 100); cout<<"Enter a substring:"; cin.getline(substr, 20); cout<<"This substring appears "<<str_count(substr, str)<<" times"<<endl; system("pause"); return 0; }
// 用 string 取代 C string, 同样希望用 Dev , 用VC编译在输入上会出问题, 这是VC的一个 Bug
#include <iostream> #include <string> #include <cstdlib> using namespace std;
int str_count(string substr, string str) { int substr_length = substr.length(); int count = 0; string temp = str; int loc = 0; if(substr_length == 0 || str.length() == 0) return 0; else { do { loc = temp.find(substr); if(loc != string::npos) { count++; temp = temp.assign(temp, loc+substr_length, temp.length()); } else break; }while(1); } return count; }
int main() { string str, substr; cout<<"Enter a string:"; getline(cin, str); cout<<"Enter a substring:"; getline(cin, substr); cout<<"This substring appears "<<str_count(substr, str)<<" times"<<endl; system("pause"); return 0; }
// 关于函数 getline 请点击以下连接
以下是这两个函数
#include <iostream> #include <cstdlib> using namespace std;
long zui_da_gong_yue_shu(long a, long b) { for( ;(a = a%b) && (b = b%a); ) ; return (a|b); } long zui_xiao_gong_bei_shu(long a, long b) { return a*b/zui_da_gong_yue_shu(a, b); }
int main() { int a = 15; // 作为测试取了两个值,你也可以取别的数值 int b = 25; int result = zui_da_gong_yue_shu(a, b); // 只是传值运算, a, b 本身并未得到改变 cout<<result<<endl; // 输出运算结果来测试正确与否 cout<<a<<" "<<b<<endl; // 输出 a, b 确定其未得到改变 //////////////////////////////////////// 以下同样,只是测试最小公倍数的运行 result = zui_xiao_gong_bei_shu(a, b); cout<<result<<endl; cout<<a<<" "<<b<<endl; system("pause"); return 0; }