1.字符串中查找字符或字符串并返回索引,字符串中提取字符或字符串
函数find_first_of() 查找在字符串中第1个出现的字符c,而函数find_last_of()查找最后一个出现的c。匹配的位置是返回值。如果没有匹配发生,则函数返回-1。
int find_first_of(char c, int start = 0):以索引为start为开头,往字符串后搜寻字符c,匹配的位置是返回值。如果没有匹配发生,则函数返回-1。
int find_last_of(char c, int start = 0):以索引为start为开头,往字符串前搜寻字符c,匹配的位置是返回值。如果没有匹配发生,则函数返回-1。
string str = "Mississippi";
int index;
index = str.find_first_of('s',0); // index为 2
index = str.find_first_of('s',4); // index为 5
index = str.find_first_of('s',7); // index为 -1
index = str.find_last_of('s',3);//index为 3
basic_string substr(size_type _Off = 0,size_type _Count = npos) const;
_Off: 所需的子字符串的起始位置。字符串中第一个字符的索引为 0,默认值为0.
_Count:复制的字符数目
返回值:一个子字符串,从其指定的位置开始
如果substr只有一个参数,则一直复制字符串直至字符串的末尾
string str1 = "helloworld";
string str2 = str1.substr(0, 2);
cout<<str2;// str2为 he
string str3 = str1.substr(1);
cout<<str3;// str3为 elloworld
find:
example:
string fullname = "Mark Tompkin", firstname, lastname;
int index;
index = fullname.find_last_of(' '); // index is 4
// firstname = "Mark" lastname = "Tompkin"
firstname = fullname.substr(0,index);
lastname = fullname.substr(index+1);
cout<<firstname<<endl;//firstname为Mark
cout<<lastname<<endl;//lastname为Tompkin
char *s1 = "kin";
string s2 = "omp";
index = fullname.find(s1);
index = fullname.find(s2, 0);
index = fullname.find("omp",7);
index = fullname.find('n',3); // index is 11
extern char *strstr(char *str1, const char *str2);
str1: 被查找目标 string expression to search.
str2: 要查找对象 The string expression to find
返回值:若str2是str1的子串,则返回str2在str1的首次出现的地址;如果str2不是str1的子串,则返回NULL。
char *str1 = "helloworld";
char *str2 = "owo";
char *str3 = strstr(str1, str2);
cout<<str3;// str3为 oworld
strchr函数原型:extern char *strchr(const char *s,char c);
函数功能:查找字符串s中首次出现字符c的位置。
strrchr函数原型:char *strrchr(const char *str, char c);
函数功能:查找一个字符c在另一个字符串str中末次出现的位置(也就是从str的右侧开始查找字符c首次出现的位置),并返回这个位置的地址。如果未能找到指定字符,那么函数将返回NULL。使用这个地址返回从最后一个字符c到str末尾的字符串。
char *str1 = "helloworld";
char c = 'o';
char *str2 = strchr(str1, c);
cout<<str2;// str2为 oworld
char *str3 = strrchr(str1, c);
cout<<str3;// str3为 orld
2.添加和删除字符串
string str;
if(str.empty()) //如果字符串str长度为0则返回true,否则返回false
//string::npos是一个常数,用来表示不存在的位置
if(str.find(".xml") == string::npos)//如果字符串str中不存在子字符串“.xml”则返回true

本文详细介绍了C++中字符串的基本操作方法,包括查找、提取、添加及删除等实用技巧,并通过示例展示了如何使用find、substr、insert和erase等函数进行高效字符串处理。

7172

被折叠的 条评论
为什么被折叠?



