C++中string的学习体会:
string:
1).不允许把两个字符串字面值连接起来,一个string对象+字符串字面值返回的是string对象.
string::size_type只是string里方便移植性的定义的一种类型
2).cout<<"/""<<s2输出的是s2本身所代表的字符串??
3).读入两个string对象,测试他们的大小,若不相等,指出两者中较大者
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout<<"Please Enter two strings: "<<endl;
//read input two strings
string s1,s2;
cin>>s1>>s2;
//test the two strings
if(s1==s2)
cout<<"they are equal."<<endl;
else if(s1>s2)
cout<<"/""<<s1<<"is bigger than"
<<"/""<<s2<<"/""<<endl;
else
cout<<"/""<<s2<<"is bigger than"
<<"/""<<s1<<"/""<<endl;
return 0;
}
4).读入两个string对象,测试他们长度是否相等
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout<<"Please Enter two Strings: "<<endl;
//read input
string s1,s2;
cin>>s1>>s2;
string::size_type len_s1,len_s2;
len_s1=s1.size();
len_s2=s2.size();
//test their length
if(len_s1==len_s2)
cout<<"they have same length"<<endl;
else if(len_s1>len_s2)
cout<<"/""<<s1<<"is longger than "
<<"/""<<s2<<endl;
else
cout<<"/""<<s2<<"is longger than"
<<"/""<<s1<<endl;
return 0;
}
5).从标准输入读取多个string对象,把它们连接到一起存放到更大的string对象中,并输出连接后的对象,改写程序,将连接后相邻的string对象以空格隔开
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout<<"Please Enter Strings((Ctrl+Z) to end): "<<endl;
string result_str,str;
//read input many strings
while(cin>>str)
result_str+=str;
//output after union:
cout<<"String equal to the concatenation of these strings is: "
<<endl<<result_str<<endl;
return 0;
}
改写后:以空格隔开输出:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout<<"Please Enter Strings((Ctrl+Z) to end): "<<endl;
string result_str,str;
//read input the first string
cin>>result_str;
while(cin>>str)
result_str+=" "+str;
//after union:
cout<<"String equal to the concatenation of these strings is: "<<endl
<<result_str<<endl;
return 0;
}
6).从string对象中去掉标点符号,要求输入到程序中的字符串必须含有标点符号,输出结果则是去掉标点符号后的string对象.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s,result_str;
bool has_punct=false; //用于标识字符串中有无标点
char ch;
//输入字符串
cout<<"Enter a string: "<<endl;
getline(cin,s);
//处理字符串:去掉其中的标点
for(string::size_type index=0;index!=s.size();++index)
{
ch=s[index];
if(ispunct(ch))
has_punct=true;
else
result_str+=ch;
}
if(has_punct)
cout<<"Result: "<<endl<<result_str<<endl;
else {
cout<<"No punctuation character in the string?! "<<endl;
return -1;
}
return 0;
}