AI刷题之字符串操作 | 豆包MarsCode AI刷题

126 阅读8分钟

本文为青训营笔记 选择豆包MarsCode AI 刷题(代码练习)题库中a替换函数 - MarsCode数字字符串格式化 - MarsCode思路详解

引言

欢迎踏上字符串处理的奇妙之旅!在编程的世界里,字符串是构建和交流的基础。无论是处理用户输入、构建网页内容、还是解析配置文件,我们几乎每天都在与字符串打交道。掌握字符串操作的艺术,就像是拥有了打开编程宝库的钥匙。

我们将通过两个豆包AI刷题具体的编程问题,深入探索字符串操作的奥秘。

通过这些练习,你将了解如何:

1. 将字符串中的特定字符替换为另一个字符串,比如将所有的 'a' 替换为 "%100"。

2. 格式化数字字符串,添加千分位逗号并去除无用的前导零。

3. C++与Python常见的字符串操作函数

一,字符串操作入门:替换字符为字符串

在编程中,字符串操作是一项基本而重要的技能。无论是处理用户输入、解析数据还是构建输出,我们都需要对字符串进行各种操作。本教程将通过一个具体的例子来介绍如何替换字符串中的特定字符为另一个字符串。

问题描述

给定一个字符串 s,我们需要编写一个函数,将字符串中的所有小写字母 'a' 替换为 "%100",并返回替换后的字符串。a替换函数 - MarsCode

示例

  • 输入:"abcdwa"
  • 输出:"%100bcdw%100"

代码实现

步骤 1:包含必要的头文件

在 C++ 中,操作字符串需要包含 <string> 头文件。

cpp
#include <string>

步骤 2:编写替换函数

我们将编写一个函数 solution,它接受一个 const std::string& s 作为参数,并返回一个 std::string

cpp
std::string solution(const std::string& s) {
    // 你的代码将在这里实现
}

步骤 3:遍历字符串并替换字符

我们将使用 std::string::find 方法来查找字符 'a' 的位置,并使用 std::string::replace 方法进行替换。

cpp
std::string solution(const std::string& s) {
    std::string result = s;
    std::string::size_type pos = 0;
    while ((pos = result.find('a', pos)) != std::string::npos) {
        result.replace(pos, 1, "%100");
        pos += 3; // 移动到替换后的字符串的下一个位置
    }
    return result;
}

步骤 4:处理边界情况

在上述代码中,我们还需要确保在替换后更新 pos 的位置,以避免无限循环。

完整代码

cpp
#include <string>

std::string solution(const std::string& s) {
    std::string result = s;
    std::string::size_type pos = 0;
    while ((pos = result.find('a', pos)) != std::string::npos) {
        result.replace(pos, 1, "%100");
        pos += 3; // 移动到替换后的字符串的下一个位置
    }
    return result;
}

测试样例

我们可以通过以下测试样例来验证我们的函数是否正确:

cpp
#include <iostream>

int main() {
    std::cout << solution("abcdwa") << std::endl;  // 输出:%100bcdw%100
    std::cout << solution("banana") << std::endl; // 输出:b%100n%100n%100
    std::cout << solution("apple") << std::endl;  // 输出:%100pple
    return 0;
}

通过第一个例题,我们学习了如何在 C++ 中操作字符串,特别是如何将字符串中的特定字符替换为另一个字符串。我们使用了 std::string::findstd::string::replace 方法来实现这一功能。这些技能在处理文本数据时非常有用,希望能帮助你掌握这些基本的字符串操作技巧。

二,数字字符串格式化:添加千分位逗号和精简前导零

在处理数字数据时,我们经常需要将数字格式化为更易读的形式。本例题将指导你如何将不带千分位逗号的数字字符串转换为带千分位逗号的格式,并去除数字字符串前面的无用0。

问题描述

给定一个数字字符串 s,我们需要编写一个函数,将其转换为带千分位逗号的格式,并保留小数部分。同时,需要精简掉数字字符串前面的无用0。数字字符串格式化 - MarsCode

示例

  • 输入:"1294512.12412"
  • 输出:"1,294,512.12412"

代码实现

步骤 1:包含必要的头文件

在 C++ 中,操作字符串需要包含 <string> 头文件。

cpp
#include <string>

步骤 2:编写格式化函数

我们将编写一个函数 solution,它接受一个 const std::string& s 作为参数,并返回一个 std::string

cpp
std::string solution(const std::string& s) {
    // 你的代码将在这里实现
}

步骤 3:去除前导零

我们将使用 std::string::find_first_not_of 方法来找到第一个非零字符的位置,并去除前导零。

cpp
std::string solution(const std::string& s) {
    size_t start = s.find_first_not_of('0');
    std::string trimmed = (start == std::string::npos) ? "0" : s.substr(start);
}

步骤 4:处理小数点和整数部分

我们将找到小数点的位置,并将整数部分和小数部分分别处理。

cpp
size_t dotPos = trimmed.find('.');
std::string integerPart = (dotPos == std::string::npos) ? trimmed : trimmed.substr(0, dotPos);
std::string decimalPart = (dotPos == std::string::npos) ? "" : trimmed.substr(dotPos);

步骤 5:添加千分位逗号

我们将在整数部分添加千分位逗号。

cpp
int n = integerPart.length();
int commaCount = (n - 1) / 3;
std::string result;
for (int i = 0; i < n; ++i) {
    result += integerPart[i];
    if ((n - i - 1) % 3 == 0 && i != n - 1) {
        result += ',';
    }
}

步骤 6:拼接小数部分

最后,我们将小数部分拼接到结果字符串中。

cpp
result += decimalPart;

完整代码

cpp
#include <string>

std::string solution(const std::string& s) {
    size_t start = s.find_first_not_of('0');
    std::string trimmed = (start == std::string::npos) ? "0" : s.substr(start);

    size_t dotPos = trimmed.find('.');
    std::string integerPart = (dotPos == std::string::npos) ? trimmed : trimmed.substr(0, dotPos);
    std::string decimalPart = (dotPos == std::string::npos) ? "" : trimmed.substr(dotPos);

    int n = integerPart.length();
    int commaCount = (n - 1) / 3;
    std::string result;
    for (int i = 0; i < n; ++i) {
        result += integerPart[i];
        if ((n - i - 1) % 3 == 0 && i != n - 1) {
            result += ',';
        }
    }

    result += decimalPart;

    return result;
}

测试样例

我们可以通过以下测试样例来验证我们的函数是否正确:

cpp
#include <iostream>

int main() {
    std::cout << solution("1294512.12412") << std::endl;  // 输出:1,294,512.12412
    std::cout << solution("0000123456789.99") << std::endl; // 输出:123,456,789.99
    std::cout << solution("987654321") << std::endl;  // 输出:987,654,321
    return 0;
}

通过第二个样例,我们学习了如何在 C++ 中操作字符串,如何将不带千分位逗号的数字字符串转换为带千分位逗号的格式,并去除数字字符串前面的无用0。我们使用了 std::string::find_first_not_ofstd::string::findstd::string::substr 方法来实现这一功能。这些技能在处理文本数据时非常有用。

常见字符串操作函数拓展

C++ 字符串操作函数

1. 长度获取

  • size() 或 length():返回字符串的长度。

    cpp
    std::string str = "Hello";
    int len = str.size(); // 或者 str.length();
    

2. 输入输出

  • 使用流操作符 << 和 >> 来输出和输入字符串。

    cpp
    std::string str;
    std::cin >> str; // 输入字符串
    std::cout << str; // 输出字符串
    

3. 子串截取

  • substr(size_t pos, size_t len):从位置 pos 开始截取长度为 len 的子串。

    cpp
    std::string str = "Hello World";
    std::string sub = str.substr(0, 5); // "Hello"
    

4. 查找子串

  • find(string str, size_t pos):查找子串 str 在主串中的位置,从 pos 开始查找。

    cpp
    std::string str = "Hello World";
    size_t pos = str.find("World"); // 返回 6
    

5. 替换子串

  • replace(size_t pos, size_t len, string str):从 pos 开始替换长度为 len 的部分为 str

    cpp
    std::string str = "Hello World";
    str.replace(6, 5, "there"); // "Hello there"
    

6. 插入字符串

  • insert(size_t index, string str):在 index 位置插入 str

    cpp
    std::string str = "Hello";
    str.insert(5, " World"); // "Hello World"
    

7. 删除字符

  • erase(size_t index, size_t count):从 index 开始删除 count 个字符。

    cpp
    std::string str = "Hello World";
    str.erase(6, 5); // "Hello W"
    

8. 排序

  • sort():对字符串中的字符进行排序。

    cpp
    std::string str = "dlroW olleH";
    std::sort(str.begin(), str.end()); // "Hello World"
    

9. 复制字符串

  • copy(size_t index, size_t len, string dest):从 index 开始复制 len 个字符到 dest

    cpp
    std::string str = "Hello";
    char dest[6];
    str.copy(0, 5, dest); // "Hello"
    

10. 添加字符

  • push_back(char ch):在字符串末尾添加一个字符。

    cpp
    std::string str = "Hello";
    str.push_back('!'); // "Hello!"
    

Python 字符串操作函数

1. 查询

  • find():查找子串第一次出现的位置,如果找不到返回 -1

    python
    str = "Hello World"
    pos = str.find("World")  # 返回 6
    

2. 大小写转换

  • upper():转换为大写。

  • lower():转换为小写。

    python
    str = "Hello World"
    upper_str = str.upper()  # "HELLO WORLD"
    lower_str = str.lower()  # "hello world"
    

3. 对齐

  • center(width, fillchar):使字符串居中,使用 fillchar 填充至 width 长度。

    python
    str = "Hello"
    centered_str = str.center(10, '*')  # "*****Hello*****"
    

4. 分割合并

  • split():以某个字符为分隔符分割字符串。

  • join():以某个字符为连接符合并字符串。

    python
    str = "Hello World"
    parts = str.split(" ")  # ["Hello", "World"]
    joined_str = " ".join(parts)  # "Hello World"
    

5. 替换

  • replace(old, new, max):将 old 替换为 new,最多替换 max 次。

    python
    str = "Hello World"
    replaced_str = str.replace("World", "Python")  # "Hello Python"
    

6. 去除两端多余字符

  • strip():去除字符串两端的空格或指定字符。

    python
    str = "  Hello World  "
    stripped_str = str.strip()  # "Hello World"
    

7. 判断开头结尾

  • startswith():检查字符串是否以指定子串开头。

  • endswith():检查字符串是否以指定子串结尾。

    python
    str = "Hello World"
    startswith_true = str.startswith("Hello")  # True
    endswith_true = str.endswith("World")  # True
    

8. 字符串计数

  • count():计算子串在字符串中出现的次数。

    python
    str = "Hello World"
    count = str.count("l")  # 3
    

9. 编码与解码

  • encode():将字符串编码为指定格式。

  • decode():将编码的字符串解码为原始格式。

    python
    str = "Hello World"
    encoded_str = str.encode('utf-8')  # b'Hello World'
    decoded_str = encoded_str.decode('utf-8')  # "Hello World"
    

总结

通过我分享的两个豆包MarsCode AI刷题中两个例题,我相信你已经对字符串操作有一个初步的了解, 在实际编程中,我们不会再使用字符数组再对字符进行繁琐的操作,字符串操作是一项基本技能,掌握它将使你能够解决更多种类的问题。希望本笔记为你的编程之旅提供了一个良好的起点。继续探索和实践,你会发现更多有趣的字符串操作技巧。