C++字符串操作详解

字符串是编程中最常用的数据类型之一,C++提供了强大的字符串处理能力。
在这里插入图片描述

1. 字符串基础

1.1 头文件和命名空间

#include <iostream>
#include <string>
#include <algorithm> // 用于字符串算法

using namespace std;

1.2 字符串声明和初始化

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

int main() {
    // 多种初始化方式
    string str1;                    // 空字符串
    string str2 = "Hello World";    // 使用C风格字符串初始化
    string str3("C++ String");      // 构造函数初始化
    string str4(5, 'A');           // 重复字符 "AAAAA"
    string str5 = str2;            // 拷贝初始化
    
    cout << "str1: " << str1 << endl;
    cout << "str2: " << str2 << endl;
    cout << "str3: " << str3 << endl;
    cout << "str4: " << str4 << endl;
    cout << "str5: " << str5 << endl;
    
    return 0;
}

2. 基本字符串操作

2.1 字符串长度和容量

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

int main() {
    string str = "Hello C++";
    
    cout << "字符串: " << str << endl;
    cout << "长度: " << str.length() << endl;      // 或 str.size()
    cout << "容量: " << str.capacity() << endl;
    cout << "是否为空: " << (str.empty() ? "是" : "否") << endl;
    
    // 调整容量
    str.reserve(50);
    cout << "调整后容量: " << str.capacity() << endl;
    
    return 0;
}

2.2 字符串访问和修改

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

int main() {
    string str = "Hello World";
    
    // 访问单个字符
    cout << "第一个字符: " << str[0] << endl;
    cout << "第二个字符: " << str.at(1) << endl;
    
    // 修改字符
    str[0] = 'h';
    str.at(6) = 'w';
    cout << "修改后: " << str << endl;
    
    // 获取C风格字符串
    const char* c_str = str.c_str();
    cout << "C风格字符串: " << c_str << endl;
    
    // 获取子字符串
    string sub = str.substr(6, 5); // 从位置6开始,取5个字符
    cout << "子字符串: " << sub << endl;
    
    return 0;
}

3. 字符串连接和比较

3.1 字符串连接

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

int main() {
    string str1 = "Hello";
    string str2 = "World";
    
    // 使用+运算符连接
    string result1 = str1 + " " + str2;
    cout << "连接结果1: " << result1 << endl;
    
    // 使用append函数
    string result2 = str1;
    result2.append(" ").append(str2);
    cout << "连接结果2: " << result2 << endl;
    
    // 使用+=运算符
    string result3 = str1;
    result3 += " ";
    result3 += str2;
    cout << "连接结果3: " << result3 << endl;
    
    return 0;
}

3.2 字符串比较

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

int main() {
    string str1 = "apple";
    string str2 = "banana";
    string str3 = "apple";
    
    // 使用比较运算符
    cout << str1 << " == " << str2 << " : " << (str1 == str2 ? "true" : "false") << endl;
    cout << str1 << " == " << str3 << " : " << (str1 == str3 ? "true" : "false") << endl;
    cout << str1 << " < " << str2 << " : " << (str1 < str2 ? "true" : "false") << endl;
    
    // 使用compare函数
    int result = str1.compare(str2);
    if (result == 0) {
        cout << "字符串相等" << endl;
    } else if (result < 0) {
        cout << str1 << " 小于 " << str2 << endl;
    } else {
        cout << str1 << " 大于 " << str2 << endl;
    }
    
    return 0;
}

4. 字符串搜索和修改

4.1 字符串搜索

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

int main() {
    string text = "The quick brown fox jumps over the lazy dog";
    string word = "fox";
    
    // 查找子字符串
    size_t pos = text.find(word);
    if (pos != string::npos) {
        cout << "找到 '" << word << "' 在位置: " << pos << endl;
    } else {
        cout << "未找到 '" << word << "'" << endl;
    }
    
    // 从指定位置开始查找
    pos = text.find("the", 10);
    if (pos != string::npos) {
        cout << "从位置10开始找到 'the' 在位置: " << pos << endl;
    }
    
    // 反向查找
    pos = text.rfind("o");
    if (pos != string::npos) {
        cout << "最后一个 'o' 在位置: " << pos << endl;
    }
    
    // 查找字符集合中的任意字符
    pos = text.find_first_of("aeiou");
    if (pos != string::npos) {
        cout << "第一个元音字母在位置: " << pos << endl;
    }
    
    return 0;
}

4.2 字符串替换和插入

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

int main() {
    string text = "I like cats";
    
    // 替换子字符串
    text.replace(7, 4, "dogs"); // 从位置7开始,替换4个字符
    cout << "替换后: " << text << endl;
    
    // 插入字符串
    text.insert(6, "small ");
    cout << "插入后: " << text << endl;
    
    // 删除字符
    text.erase(6, 6); // 从位置6开始,删除6个字符
    cout << "删除后: " << text << endl;
    
    return 0;
}

5. 字符串和数值转换

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

int main() {
    // 数值转字符串
    int num = 12345;
    string str_num = to_string(num);
    cout << "整数转字符串: " << str_num << endl;
    
    double pi = 3.14159;
    string str_pi = to_string(pi);
    cout << "浮点数转字符串: " << str_pi << endl;
    
    // 字符串转数值
    string str_int = "6789";
    int converted_int = stoi(str_int);
    cout << "字符串转整数: " << converted_int << endl;
    
    string str_double = "2.71828";
    double converted_double = stod(str_double);
    cout << "字符串转浮点数: " << converted_double << endl;
    
    // 处理转换异常
    try {
        string invalid = "abc";
        int result = stoi(invalid);
    } catch (const invalid_argument& e) {
        cout << "无效参数异常: " << e.what() << endl;
    } catch (const out_of_range& e) {
        cout << "超出范围异常: " << e.what() << endl;
    }
    
    return 0;
}

6. 字符串算法应用

6.1 字符串转换

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;

int main() {
    string text = "Hello World";
    
    // 转换为大写
    string upper = text;
    transform(upper.begin(), upper.end(), upper.begin(), ::toupper);
    cout << "大写: " << upper << endl;
    
    // 转换为小写
    string lower = text;
    transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
    cout << "小写: " << lower << endl;
    
    // 反转字符串
    string reversed = text;
    reverse(reversed.begin(), reversed.end());
    cout << "反转: " << reversed << endl;
    
    return 0;
}

6.2 字符串分割

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

// 字符串分割函数
vector<string> split(const string& str, char delimiter) {
    vector<string> tokens;
    string token;
    istringstream tokenStream(str);
    
    while (getline(tokenStream, token, delimiter)) {
        tokens.push_back(token);
    }
    
    return tokens;
}

int main() {
    string text = "apple,banana,cherry,date";
    
    vector<string> fruits = split(text, ',');
    
    cout << "分割结果:" << endl;
    for (const auto& fruit : fruits) {
        cout << "- " << fruit << endl;
    }
    
    return 0;
}

7. 综合示例:字符串处理工具

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;

class StringUtils {
public:
    // 统计单词数量
    static int countWords(const string& text) {
        istringstream iss(text);
        int count = 0;
        string word;
        
        while (iss >> word) {
            count++;
        }
        
        return count;
    }
    
    // 检查是否为回文
    static bool isPalindrome(const string& text) {
        string cleanText;
        
        // 移除空格和标点,转换为小写
        for (char c : text) {
            if (isalnum(c)) {
                cleanText += tolower(c);
            }
        }
        
        string reversed = cleanText;
        reverse(reversed.begin(), reversed.end());
        
        return cleanText == reversed;
    }
    
    // 去除首尾空格
    static string trim(const string& text) {
        size_t start = text.find_first_not_of(" \t\n\r");
        size_t end = text.find_last_not_of(" \t\n\r");
        
        if (start == string::npos) {
            return "";
        }
        
        return text.substr(start, end - start + 1);
    }
};

int main() {
    string text = "  A man a plan a canal Panama  ";
    
    cout << "原始文本: '" << text << "'" << endl;
    cout << "单词数量: " << StringUtils::countWords(text) << endl;
    cout << "去除空格: '" << StringUtils::trim(text) << "'" << endl;
    cout << "是否为回文: " << (StringUtils::isPalindrome(text) ? "是" : "否") << endl;
    
    return 0;
}

总结

C++的字符串操作非常强大和灵活,主要特点包括:

  1. 安全性:std::string自动管理内存,避免缓冲区溢出
  2. 灵活性:提供了丰富的成员函数进行各种操作
  3. 兼容性:可以与C风格字符串无缝交互
  4. 高效性:现代C++编译器对字符串操作有很好的优化

掌握这些字符串操作技巧对于C++编程至关重要,它们在实际开发中有着广泛的应用。

(注:文档部分内容可能由 AI 生成)

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐