doc/notebook/docs/C++/3.string.md

2.7 KiB
Raw Permalink Blame History

  1. std::string: C++中的字符串类,提供了丰富的成员函数用于字符串操作。常用的成员函数包括:

    • size(): 返回字符串的长度。
    • length(): 返回字符串的长度。
    • empty(): 判断字符串是否为空。
    • clear(): 清空字符串内容。
    • substr(pos, len): 返回从位置pos开始长度为len的子字符串。
    • find(str, pos): 在字符串中查找子字符串str,并返回第一次出现的位置。
    • replace(pos, len, str): 替换字符串中从位置pos开始长度为len的子串为字符串str
    • append(str): 在字符串末尾追加字符串str
    • insert(pos, str): 在指定位置插入字符串str
    #include <iostream>
    #include <string>
    
    int main() {
        std::string str = "Hello, world!";
    
        // 使用成员函数进行字符串操作
        std::cout << "Length: " << str.length() << std::endl;
        std::cout << "Substring: " << str.substr(0, 5) << std::endl;
    
        str.replace(7, 5, "C++");
        std::cout << "Replaced: " << str << std::endl;
    
        str.append(" Goodbye!");
        std::cout << "Appended: " << str << std::endl;
    
        str.insert(0, "Greetings, ");
        std::cout << "Inserted: " << str << std::endl;
    
        return 0;
    }
    
  2. std::getline(): 从输入流中读取一行数据并存储到字符串中。

    #include <iostream>
    #include <string>
    
    int main() {
        std::string line;
        std::cout << "Enter a line of text: ";
        std::getline(std::cin, line);
        std::cout << "You entered: " << line << std::endl;
    
        return 0;
    }
    
  3. 字符串查找和比较函数:

    • std::string::find(str, pos): 在字符串中查找子字符串str,并返回第一次出现的位置。
    • std::string::rfind(str, pos): 在字符串中从后向前查找子字符串str,并返回第一次出现的位置。
    • std::string::find_first_of(str, pos): 在字符串中查找任意字符集合str中的字符,返回第一次出现的位置。
    • std::string::find_last_of(str, pos): 在字符串中从后向前查找任意字符集合str中的字符,返回第一次出现的位置。
    • std::string::compare(str): 比较字符串与str返回大小关系0表示相等负数表示小于正数表示大于
    #include <iostream>
    #include <string>
    
    int main() {
        std::string str = "Hello, world!";
    
        if (str.find("world") != std::string::npos) {
            std::cout << "Substring found!" << std::endl;
        }
    
        if (str.compare("Hello, C++!") == 0) {
            std::cout << "Strings are equal." << std::endl;
        }
    
        return 0;
    }