手把手教程:C++字符串

本文详细介绍了C++中字符串的基础知识,包括字符串定义(字符数组和string类)、常用操作(如长度、插入、替换等)、比较运算符、stringstream的使用以及内存管理,通过实例演示了这些概念的实际应用。
摘要由CSDN通过智能技术生成

信息学奥赛手把手教程第一节:字符串

基础知识:

在C++中,字符串是字符的序列,可以用多种方式表示和处理。以下是一些基本的字符串知识:
基础知识在C++中,字符串可以通过以下两种方式定义:
字符数组:这是一种较为传统的方式,你可以创建一个字符数组,并使用字符串字面量来初始化它。例如:

char str[] = "Hello, World!";

string类:C++标准库中包含了一个string类,你可以使用它来创建和操作字符串。例如:

#include <string>
std::string str = "Hello, World!";

字符串操作:

字符串操作 C++的string类提供了许多用于操作字符串的方法,如:

length()size():这两个方法都可以返回字符串的长度。
append():这个方法可以在字符串的末尾添加字符或字符串。
insert():这个方法可以在字符串的指定位置插入字符或字符串。
erase():这个方法可以删除字符串中的字符。
replace():这个方法可以替换字符串中的字符。
find():这个方法可以查找子字符串在字符串中的位置。
substr():这个方法可以返回字符串的一个子串。

字符串操作示例

代码示例:

  1. length() 或 size()
std::string str = "Hello, World!";
std::cout << str.length();  // 输出:12
std::cout << str.size();    // 输出:12

  1. append()
std::string str = "Hello";
str.append(", World!");  // str现在是"Hello, World!"

  1. insert()
std::string str = "Hello World!";
str.insert(5, ",");  // str现在是"Hello, World!"

  1. erase()
std::string str = "Hello, World!";
str.erase(5, 1);  // str现在是"Hello World!"

  1. replace()
std::string str = "Hello, World!";
std::size_t found = str.find("World");
if (found!=std::string::npos)
    std::cout << "'World' found at: " << found << '\n';

  1. find()
std::string str = "Hello, World!";
std::size_t found = str.find("World");
if (found!=std::string::npos)
    std::cout << "'World' found at: " << found << '\n';

  1. substr()
std::string str = "Hello, World!";
std::string sub = str.substr(0, 5);  // sub现在是"Hello"

字符串的比较

字符串的比较 C++允许你使用比较运算符(如==,!=,<,>)来比较两个字符串。这些运算符会按字典顺序比较字符串。

比较运算符示例

这是一个C++代码示例,展示了如何使用比较运算符:

#include <iostream>

int main() {
    // 定义两个整数
    int a = 10;
    int b = 20;

    // 使用比较运算符
    std::cout << "a == b: " << (a == b) << "\n";
    std::cout << "a != b: " << (a != b) << "\n";
    std::cout << "a > b: " << (a > b) << "\n";
    std::cout << "a < b: " << (a < b) << "\n";
    std::cout << "a >= b: " << (a >= b) << "\n";
    std::cout << "a <= b: " << (a <= b) << "\n";

    return 0;
}

这个程序首先定义了两个整数,然后使用了各种比较运算符(等于、不等于、大于、小于、大于等于和小于等于)来比较这两个整数。

字符串流

字符串流 C++的stringstream类允许你将字符串作为流来操作,这对于执行复杂的字符串操作非常有用。例如,你可以使用stringstream来分割字符串,或者将其他类型的数据转换为字符串。
用法:
stringstream是C++中非常有用的一个类,它可以让你像操作流一样操作字符串。以下是一些基本的使用方法和示例:

  1. 创建stringstream对象 你可以通过以下方式创建一个stringstream对象:

字符串流示例

#include <sstream>
std::stringstream ss;

  1. 向stringstream中添加数据 你可以使用插入运算符(<<)向stringstream中添加数据。例如:
ss << "Hello, World!";

  1. 从stringstream中读取数据 你可以使用提取运算符(>>)从stringstream中读取数据。例如:
std::string word;
ss >> word;  // word现在是"Hello,"

  1. 使用str()方法 str()方法可以用来获取或设置stringstream中的字符串。例如:
std::string s = ss.str();  // 获取字符串
ss.str("New string");  // 设置新的字符串

  1. 使用clear()方法 clear()方法可以用来清除stringstream的错误标志,例如:
ss.clear();

以下是一些使用stringstream的示例:
示例1:计算字符串中的单词数

#include <iostream>
#include <sstream>
#include <string>

int countWords(const std::string& str) {
    std::stringstream ss(str);
    std::string word;
    int count = 0;
    while (ss >> word)
        count++;
    return count;
}

int main() {
    std::string s = "geeks for geeks geeks contribution placements";
    std::cout << "Number of words are: " << countWords(s) << std::endl;
    return 0;
}

示例2:打印字符串中各单词的频率

#include <bits/stdc++.h>
using namespace std;

void printFrequency(const std::string& st) {
    map<string, int> FW;
    stringstream ss(st);
    string Word;
    while (ss >> Word)
        FW[Word]++;
    for (auto m : FW)
        cout << m.first << "->" << m.second << "\n";
}

int main() {
    string s = "Geeks For Geeks Ide";
    printFrequency(s);
    return 0;
}

示例3:将整数转换为字符串

#include <iostream>
#include <sstream>
using namespace std;

int main() {
    int val = 123;
    stringstream geek;
    geek << val;
    string x;
    geek >> x;
    cout << x + "4" << endl;  // 输出:1234
    return 0;
}

字符串的内存管理

在C++中,字符串的内存管理是自动的,主要由string类负责。以下是一些关于C++字符串内存管理的基本知识:

  1. 字符串的内存分配 在C++中,string对象实质上就是一个容器,其内部有一个c_str方法能够返回一个指向实质存储字符串副本的数据成员1。当你创建一个string对象时,C++会为你分配内存。当string对象不再需要时,C++会自动释放内存1。

  2. 字符串的内存扩容 当string对象需要增大时,由于相邻的内存可能被占用,因此需要分配一个新的内存块,并将原来的内存赋值到新的内存块中2。这样会降低效率。所以C++实现分配了一个比实际字符串大的内存块,如果字符串不断增大,超过了内存块大小,程序将分配一个大小为原理两倍的新内存块,以提供足够的空间2。

  3. 字符串的内存释放 在C++中,当一个string对象的生命周期结束时,C++会自动释放其占用的内存1。

  4. 字符串的内存优化 C++的string对象内部实现了小型字符串优化 (Small String Optimisation)。只要传入的字符串字面量小于一定的阀值,string内部实现在栈中分配内存。只要大于这个阀值,string对象内部会隐式执行new操作在堆中根据指定的字符串尺寸分配初次内存1。

字符串内存管理的代码示例:

这是一个简单的C++代码示例,展示了如何管理字符串的内存:

#include <iostream>
#include <string>

int main() {
    // 创建一个字符串
    std::string str = "Hello, World!";

    // 输出字符串和它的长度
    std::cout << "String: " << str << "\n";
    std::cout << "Length: " << str.length() << "\n";

    // 改变字符串的内容
    str = "Hello, World!";
    std::cout << "Modified String: " << str << "\n";

    // 清空字符串并释放内存
    str.clear();
    std::cout << "Cleared String: " << str << "\n";

    return 0;
}

这个程序首先创建了一个字符串,然后输出了它的内容和长度。接着,我们修改了字符串的内容,并输出了修改后的字符串。最后,我们清空了字符串并释放了它占用的内存。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值