今天下午把最基本的几种字符串操作总结了一下。 //功能:可以对字符串进行复制,连接,比较和倒序// /// #include <iostream> using namespace std; class string_operation { private: char str1[100]; char str2[100]; int Case; public: void welcome(); //welcome 函数用于初始化界面 void judge(); //judge函数用于判断用户需要的功能 void string_copy(); void string_link(); void string_compare(); void string_reverse(); void string_length(); void more(); }; int main() { string_operation a; a.welcome(); a.judge(); return 0; } void string_operation::welcome() { cout<<" 本程序用于字符串的复制、连接、比较和倒序"<<endl; cout<<"********************************************************************************"<<endl<<endl; cout<<"********************************************************************************"<<endl; cout<<"请先输入两个字符串"<<endl; cin>>str1>>str2; cout<<"按1进行字符串的复制"<<endl; cout<<"按2进行字符串的连接"<<endl; cout<<"按3进行字符串的比较"<<endl; cout<<"按4进行字符串的倒序"<<endl; cout<<"按5测量字符串的长度"<<endl; cout<<"按0退出程序"<<endl; cout<<"请选择您要使用的功能"; cin>>Case; } void string_operation::judge() { switch(Case) { case 1:{ string_copy(); break; } case 2:{ string_link(); break; } case 3:{ string_compare(); break; } case 4:{ string_reverse(); break; } case 5:{ string_length(); break; } case 0:{ break; } } } void string_operation:: string_copy() //字符串复制 { int i=-1; while(str1[++i]!='/0') str2[i]=str1[i]; str2[i]='/0'; cout<<"复制后的字符串为:"; cout<<str2<<endl; more(); } void string_operation:: string_link() //字符串连接 { int i=0,j=0; while(str2[i]!='/0') i++; while(str1[j]!='/0') str2[i++]=str1[j++]; str2[++i]='/0'; cout<<"连接后的字符串为:"; cout<<str2<<endl; more(); } void string_operation:: string_compare() //字符串比较 { int i=0,j=0; while(str1[i]!='/0') i++; while(str2[j]!='/0') j++; if(i>j) cout<<"较长的字符串是:"<<str1<<endl; if(i<j) cout<<"较长的字符串是:"<<str2<<endl; if(i==j) cout<<"两字符串相等"<<endl; more(); } void string_operation:: string_reverse() //字符串反转 { int count1=0,count2=0; while(str1[count1]!='/0') count1++; while(str2[count2]!='/0') count2++; int tmp1,tmp2; for(int i=0;i<count1/2;i++) { tmp1=str1[i]; str1[i]=str1[count1-1-i]; str1[count1-1-i]=tmp1; } for(int j=0;j<count2/2;j++) { tmp2=str2[j]; str2[j]=str2[count2-1-j]; str2[count2-1-j]=tmp2; } cout<<"倒序后的字符串分别为: "<<str1<<" "<<str2; more(); } void string_operation:: string_length() //字符串长度 { int i=0,j=0; while(str1[i]!='/0') i++; while(str2[j]!='/0') j++; cout<<"字符串1的长度为: "<<i<<" "; cout<<"字符串2的长度为: "<<j; more(); } void string_operation::more() { int option; cout<<"如果要继续操作,请选择功能,否则按0退出"<<endl; cin>>option; Case=option; judge(); } 粗略的用思维导图画了一张流程图: