Code前端首页关于Code前端联系我们

使用C++定义和操作字符串的技巧

terry 2年前 (2023-10-01) 阅读数 195 #c++
文章标签 MySQL Workbench

一、定义字符串

在C++中定义字符串可以使用C++11提供的std::string类,这个类的头文件是。下面是一个定义字符串的示例:

#include 
using namespace std;

int main() {
    string str = "Hello, world!";
    return 0;
}

在上面的示例中,“str”就是一个字符串变量,它的初始值是“Hello, world!”。

二、字符串的拼接和复制

C++中可以使用“+”对字符串进行拼接,例如:

#include 
using namespace std;

int main() {
    string str1 = "Hello, ";
    string str2 = "world!";
    string str3 = str1 + str2;
    return 0;
}

在上面的示例中,“str1 + str2”就是将两个字符串进行拼接生成了新的字符串“str3”。

如果需要将一个字符串复制到另一个字符串中,则可以使用“=”操作符,例如:

#include 
using namespace std;

int main() {
    string str1 = "Hello, world!";
    string str2 = str1;
    return 0;
}

在上面的示例中,“str2”就是将“str1”中的字符串复制到了“str2”中。

三、字符串的查找和截取

C++中可以使用字符串类中的find方法查找字符串中的子串,例如:

#include 
using namespace std;

int main() {
    string str = "Hello, world!";
    int pos = str.find("world");
    return 0;
}

在上面的示例中,“str.find("world")”就是查找字符串“str”中是否包含“world”子串,返回的pos就是“world”子串在“str”中的起始位置。

如果需要截取字符串中的一部分,则可以使用字符串类中的substr方法,例如:

#include 
using namespace std;

int main() {
    string str = "Hello, world!";
    string substr = str.substr(7,5);
    return 0;
}

在上面的示例中,“str.substr(7,5)”就是从字符串“str”中截取从第7个字符开始的5个字符,返回的“substr”就是截取出来的子串。

四、字符串的替换和插入

C++中可以使用字符串类中的replace方法替换字符串中的子串,例如:

#include 
using namespace std;

int main() {
    string str = "Hello, world!";
    str.replace(7,5,"China");
    return 0;
}

在上面的示例中,“str.replace(7,5,"China")”就是将字符串“str”中从第7个字符开始的5个字符替换成“China”,得到新的字符串“Hello, China!”。

如果需要在字符串中插入子串,则可以使用字符串类中的insert方法,例如:

#include 
using namespace std;

int main() {
    string str = "Hello!";
    str.insert(6," world");
    return 0;
}

在上面的示例中,“str.insert(6," world")”就是在字符串“str”中在第6个字符的位置插入子串“world”,得到新的字符串“Hello world!”。

五、字符串的转换

C++中可以使用stod、stof、stoi、stol、stoll、stoul、stoull函数将字符串转换为double、float、int、long、long long、unsigned long、unsigned long long等类型,例如:

#include 
using namespace std;

int main() {
    string str1 = "3.14";
    string str2 = "100";
    double d = stod(str1);
    int i = stoi(str2);
    return 0;
}

在上面的示例中,“stod(str1)”就是将字符串“str1”转换为double类型,得到“3.14”;“stoi(str2)”就是将字符串“str2”转换为int类型,得到“100”。

六、总结

在C++中,使用字符串类可以轻松实现字符串的定义、拼接、复制、查找、截取、替换和插入等操作,同时也可以实现字符串与其他数据类型的相互转换,这些都是在实际的C++开发过程中经常使用到的技巧。

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门