1.strcmp函数是string compare(字符串比较)的缩写,用于比较两个字符串并根据比较结果返回整数。基本形式为strcmp(str1,str2),若str1=str2,则返回零;若str1<str2,则返回负数;若str1>str2,则返回正数。
int a = strcmp(str1,str2);//str1、str2如果相同则返回0,即a=0;
2.substr是C++语言函数,主要功能是复制子字符串,要求从指定位置开始,并具有指定的长度。如果没有指定长度_Count或_Count+_Off超出了源字符串的长度,则子字符串将延续到源字符串的结尾。
std::string path = "D:\\DATA\\test";
std::string path2 = path.substr(0, 2);
std::cout << path2 << std::endl;
运行结果为:
![]()
3.npos用法(注意数据类型为string::size_type,虽然和int基本一样,但是如果需要接受find()的返回值时,需要用一个string::size_type类型的变量接收)
- npos可以表示string的结束位子,是string::type_size 类型的,也就是find()返回的类型。
- string::npos作为string的成员函数的一个长度参数时,表示“直到字符串结束(until the end of the string)”。
npos详细用法参考自: https://blog.youkuaiyun.com/jiejinquanil/article/details/51789682
4.replace()用法:
/*用法一:
*用str替换指定字符串从起始位置pos开始长度为len的字符
*string& replace (size_t pos, size_t len, const string& str);
*/
int main()
{
string line = "this@ is@ a test string!";
line = line.replace(line.find("@"), 1, ""); //从第一个@位置替换第一个@为空
cout << line << endl;
return 0;
}
运行结果:

replace参考自:C++ replace() 函数用法详解_笔记-优快云博客_replace函数怎么用
本文详细介绍了C++中常用的字符串操作方法,包括strcmp函数的使用、substr函数复制子字符串的功能、npos的含义及其应用场景,以及replace函数的具体用法。通过实际代码示例,帮助读者更好地理解和掌握这些字符串操作技巧。
393

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



