c++ String类型介绍(c++ string的常用方法及其功能)
C++ String 类型介绍
C++ string 类型是 C++ 标准库中的一种字符串类型,它是一个模板类,可以存储任意字符串,并且提供了一系列的操作函数,可以方便地操作字符串。
库函数使用
C++ string 类型提供了一系列的操作函数,可以方便地操作字符串,主要有以下几类:
- 字符串构造函数:构造一个新的字符串,可以指定字符串的长度、字符串的内容等。
- 字符串拼接函数:将两个字符串拼接起来,可以指定拼接的位置。
- 字符串查找函数:查找字符串中指定的字符或字符串,可以指定查找的起始位置。
- 字符串替换函数:替换字符串中指定的字符或字符串,可以指定替换的起始位置。
- 字符串分割函数:将字符串按照指定的字符或字符串分割成多个子字符串
- string::length() - 返回字符串的长度
- string::find() - 查找子字符串
- string::substr() - 返回字符串的子字符串
- string::replace() - 替换字符串中的子字符串
- string::append() - 将字符串添加到另一个字符串的末尾
- string::compare() - 比较两个字符串
- string::copy() - 复制字符串
应用实例
- 字符串拼接函数
#include <string>
int main()
{
std::string str1 = "Hello";
std::string str2 = "World";
std::string str3 = str1 + " " + str2;
std::cout << str3 << std::endl;
return 0;
}
C++ 中的 string 类型提供了一个 append() 方法,用于将一个字符串附加到另一个字符串的末尾。
语法:
string.append(string2);
参数:
string2:要附加的字符串
返回值: 无
示例:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1 = "Hello ";
string str2 = "World!";
str1.append(str2);
cout << str1;
return 0;
}
字符串查找函数
c++ find 是一种用于在 c++ 字符串中搜索指定字符串的函数。它可以在字符串中搜索指定的子字符串,并返回子字符串的位置。
语法:
size_t find(const string& str, const string& substr, size_t pos = 0);
参数:
- str:要搜索的字符串
- substr:要搜索的子字符串
- pos:从字符串中的指定位置开始搜索(可选)
返回值:
如果找到子字符串,则返回子字符串在字符串中的位置;如果未找到子字符串,则返回 string::npos
#include <string>
#include <iostream>
int main()
{
std::string str = "Hello World!";
std::string search_str = "World";
std::size_t found = str.find(search_str);
if (found != std::string::npos)
std::cout << "Found " << search_str << " at " << found << '\n';
else
std::cout << search_str << " not found\n";
return 0;
}
字符串分割函数
substr 是 C++ 中的一个字符串函数,它可以从一个给定的字符串中提取一个子字符串。它的语法如下:
string substr (size_t pos, size_t len) const;
其中,pos 是要提取子字符串的起始位置,len 是要提取的字符个数。
若存在错误,请指正,立即修改