string标准库类型(C++)

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;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值