C++中string类型操作字符串的基本用法

分类:知识百科 日期: 点击:0

C++中的string类型是一种字符串类型,它可以用来操作字符串。它提供了许多有用的函数,可以用来查找、替换、插入和删除字符串中的字符,以及比较两个字符串的大小等。

1. 创建字符串

可以使用string类的构造函数来创建字符串,例如:

string str1; // 创建空字符串
string str2 = "Hello World!"; // 使用字符串字面量创建字符串
string str3 = str2; // 使用已存在的字符串创建新的字符串
string str4(str3); // 使用拷贝构造函数创建新的字符串

2. 字符串比较

可以使用string类的compare函数来比较两个字符串的大小,例如:

string str1 = "Hello";
string str2 = "World";

if (str1.compare(str2) == 0)
{
    cout << "str1 and str2 are equal" << endl;
}
else if (str1.compare(str2) < 0)
{
    cout << "str1 is less than str2" << endl;
}
else
{
    cout << "str1 is greater than str2" << endl;
}

3. 查找字符串

可以使用string类的find函数来查找字符串中的字符,例如:

string str = "Hello World";

// 查找字符 'o' 的位置
size_t pos = str.find('o');
if (pos != string::npos)
{
    cout << "Found 'o' at position " << pos << endl;
}
else
{
    cout << "Character 'o' not found" << endl;
}

// 查找字符串 "World" 的位置
pos = str.find("World");
if (pos != string::npos)
{
    cout << "Found \"World\" at position " << pos << endl;
}
else
{
    cout << "String \"World\" not found" << endl;
}

4. 替换字符串

可以使用string类的replace函数来替换字符串中的字符,例如:

string str = "Hello World";

// 替换字符 'o' 为 'a'
str.replace(str.find('o'), 1, "a");

// 替换字符串 "World" 为 "Universe"
str.replace(str.find("World"), 5, "Universe");

cout << str << endl; // 输出 "Hell a Universe"

5. 插入字符串

可以使用string类的insert函数来插入字符串,例如:

string str = "Hello";

// 在字符串末尾插入字符 '!'
str.insert(str.length(), "!");

// 在字符串的第 5 个位置插入字符 ','
str.insert(4, ",");

cout << str << endl; // 输出 "Hell,o!"

6. 删除字符串

可以使用string类的erase函数来删除字符串,例如:

string str = "Hello World";

// 删除字符串的一个字符
str.erase(str.length() - 1);

// 删除字符串的第 5 个字符
str.erase(4, 1);

cout << str << endl; // 输出 "Hell World"

以上是,通过使用这些函数,可以方便地操作字符串。

标签:

版权声明

1. 本站所有素材,仅限学习交流,仅展示部分内容,如需查看完整内容,请下载原文件。
2. 会员在本站下载的所有素材,只拥有使用权,著作权归原作者所有。
3. 所有素材,未经合法授权,请勿用于商业用途,会员不得以任何形式发布、传播、复制、转售该素材,否则一律封号处理。
4. 如果素材损害你的权益请联系客服QQ:77594475 处理。