1.基本操作
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;//创建string对象
str.append("I like apple");//在文本末尾添加文本
cout<<str<<endl;
cout<<str.compare("I like app")<<endl;//比较两个字符串,比括号里的文本多几个字符
cout<<str.empty()<<endl;//判断字符是否为空,是则输出1,不是输出0
str.erase(str.begin());//删除字符
cout<<str<<endl;
str.erase(str.begin()+1);
cout<<str<<endl;
str.erase(str.end()-1);//str.end()指向最后一个字符的下一个位置
cout<<str<<endl;
cout<<"字符串是否存在a:"<<" "<<str.find('a')<<endl;//在字符串里查找字符,返回下标地址
cout<<"字符串是否存在s:"<<" "<<str.find('s')<<endl;//没有则返回str.end();
cout<<"字符串是否存在p:"<<" "<<str.find('p')<<endl;//返回第一个下标地址
cout<<str.find_first_of('p')<<endl;//返回第一个与p等值的字符,查找其位置
cout<<str<<endl;
str.insert(str.begin(),'I');//在begin的前一个位置插入一个字符
cout<<str<<endl;
str.insert(str.end(),'e');//在end的前一个位置插入一个字符
cout<<str<<endl;
cout<<str.size()<<endl;//计算字符串长度
cout<<str.length()<<endl;//计算字符串长度
str.replace(str.length(),1,"!");//替换字符 从后往前替换1个字符
cout<<str<<endl;
str.replace(str.length()-6,7,"banana!");//从后往前替换6个字符
cout<<str<<endl;
cout<<str.substr(6,6)<<endl;//返回某个子字符串 substr(n,i)从下标第n个开始,返回i个字符
//在字符串里查找单词
string::size_type loc=str.find("banana",0);//调用size_type函数,变量名loc,loc相当于一个unsigned int类型
if(loc != string::npos) //nops是未找到字符串所返回的特殊值,nops=-1
cout<<"Found banana at:"<<" "<<loc<<endl;//找到字符串,输出所在字符串的第一个字符的下标
else
cout<<"Not found"<<endl;
return 0;
2.判断一句话里有几个单词
输入样例:I am good,but you are better.
输出样例:7
include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string str;
int ch = 0;
int count = 0;
getline(cin,str);
string::iterator it;
for(it=str.begin()-1;it!=str.end();it++)
{
int i = 0;
int a = 0;
int b = 0;
if(*it==','||*it==' '||*it=='.')
count++;
}
cout<<count<<endl;
return 0;
}
3.判断一句话里有几个字母
输入样例:
I am the storm that is approaching!
输出样例:
24
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
int isalpha(int ch);
string str;
int ch = 0;
int count = 0;
getline(cin,str);
string::iterator it;
for(it=str.begin()-1;it!=str.end();it++)
{
int i = 0;
int a = 0;
int b = 0;
i = isalpha(*it);
if(i!=0)
count++;
}
cout<<count<<endl;
return 0;
}
4.判断一句话里有几个给定的单词
输入样例1:
you are a good good good person
good
输出样例1:
The number of 'good' is: 3
输入样例2:
are are are are
is
输出样例:
Not Found
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
string ch;
int count = 0;
int i = 0;
getline(cin,str);
getline(cin,ch);
for(i=0;i<str.length();)
{
if(str.find(ch,i)!=string::npos)
{
count++;
i=str.find(ch,i)+ch.size()-1;
}
else
{
break;
}
}
if(count!=0)
cout<<"The number of '"<<ch<<"' is: "<<count<<endl;
else
cout<<"Not Found"<<endl;
}