1.在字符串后面添加一个新字符
#include <iostream>
#include <string>
using namespace std;
string a, s;
int main()
{
cin >> a;//求字符串长度
int l = a.length();
a += a[0];//将第一个字符添加到末尾
return 0;
}
2.字符串的长度
1)strlen(str) ---用于求字符数组的长度
strlen(str.c_str()) 将string类型改成char类型
2)str.length() ---用于求string类对象的成员函数
3)str.size() ---用于求string类对象的成员函数
4)sizeof()
#include <string>
#include <iostream>
using namespace std;
int main()
{
string name="babababa";
cout<<name.length()<<endl;//结果是8
cout<<name.size()<<endl;//结果是8
char mail[100]="haha";
cout<<strlen(mail)<<endl;//结果是4
char *psd;
psd="lalala";
cout<<strlen(psd)<<endl;//结果是6
return 0;
}
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str = "This is a string";
cout << str.length() << endl;
cout << str.size() << endl;
return 0;
}
#include <string>
#include<iostream>
using namespace std;
int main()
{
string str = "This is a string";
char cstr[20];
strcpy_s(cstr, str.c_str());
cout << strlen(cstr) << endl;
return 0;
}
#include <string>
#include<iostream>
using namespace std;
int main()
{
string str = "This is a string";
cout << sizeof(str) << endl;
cout << sizeof(string) << endl;
cout << sizeof(int*) << endl;
return 0;
}
3.find()函数 ---
string中find()返回值是字母在母串中的位置(下标记录),如果没有找到,那么会返回一个特别的标记npos。(返回值可以看成是一个int型的数)
#include<bits/stdc++.h>//万能头
using namespace std;
string a,b;
int main()// B2118
{
cin>>a>>b;
if(b.find(a)!=string::npos) cout<<a<<" is substring of "<<b;//a是b的子串
//str.npos (表示无效),
else if(a.find(b)!=string::npos) cout<<b<<" is substring of "<<a;//b是a的子串
else cout<<"No substring";
return 0;
}
参见下面例子
#include<cstring>
#include<cstdio>
#include<iostream>
using namespace std;
int main()
{
find函数返回类型 size_type
string s("1a2b3c4d5e6f7jkg8h9i1a2b3c4d5e6f7g8ha9i");
string flag;
string::size_type position;
//find 函数 返回jk 在s 中的下标位置
position = s.find("jk");
if (position != s.npos) //如果没找到,返回一个特别的标志c++中用npos表示,我这里npos取值是4294967295,
{
printf("position is : %d\n" ,position);
}
else
{
printf("Not found the flag\n");
}
}
返回子串出现在母串中的首次出现的位置,和最后一次出现的位置。
flag = "c";
position = s.find_first_of(flag);
printf("s.find_first_of(flag) is :%d\n",position);
position = s.find_last_of(flag);
printf("s.find_last_of(flag) is :%d\n",position);
输出
查找某一给定位置后的子串的位置
//从字符串s 下标5开始,查找字符串b ,返回b 在s 中的下标
position=s.find("b",5);
cout<<"s.find(b,5) is : "<<position<<endl;
查找所有子串在母串中出现的位置
//查找s 中flag 出现的所有位置。
flag="a";
position=0;
int i=1;
while((position=s.find(flag,position))!=string::npos)
{
cout<<"position "<<i<<" : "&