MST

星途 面试题库

面试题:C++中string类的常用操作

请简述C++ string类中至少5个常用成员函数的功能及用法,并给出相应代码示例,例如substr、find、replace等。
15.2万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
  1. substr
    • 功能:返回一个子字符串,该子字符串是从原字符串指定位置开始,长度为指定值的部分。
    • 用法string substr (size_t pos = 0, size_t len = npos) const;pos是起始位置(默认为0),len是子字符串长度(默认为直到字符串末尾)。
    • 代码示例
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    std::string sub = str.substr(7, 5);
    std::cout << sub << std::endl; 
    return 0;
}
  1. find
    • 功能:查找字符串中首次出现指定子字符串或字符的位置。
    • 用法
      • size_t find (const string& str, size_t pos = 0) const; 查找子字符串str,从位置pos开始。
      • size_t find (const char* s, size_t pos = 0) const; 查找以\0结尾的字符串s,从位置pos开始。
      • size_t find (char c, size_t pos = 0) const; 查找字符c,从位置pos开始。
    • 代码示例
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    size_t pos = str.find("World");
    if (pos != std::string::npos) {
        std::cout << "Found at position: " << pos << std::endl;
    } else {
        std::cout << "Not found" << std::endl;
    }
    return 0;
}
  1. replace
    • 功能:替换字符串中指定范围内的字符为新的字符串。
    • 用法
      • string& replace (size_t pos, size_t len, const string& str); 从位置pos开始,长度为len的部分替换为str
      • string& replace (size_t pos, size_t len, const char* s); 从位置pos开始,长度为len的部分替换为以\0结尾的字符串s
    • 代码示例
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    str.replace(7, 5, "C++");
    std::cout << str << std::endl; 
    return 0;
}
  1. append
    • 功能:在字符串末尾添加内容。
    • 用法
      • string& append (const string& str); 添加字符串str
      • string& append (const char* s); 添加以\0结尾的字符串s
    • 代码示例
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello";
    str.append(", World!");
    std::cout << str << std::endl; 
    return 0;
}
  1. length / size
    • 功能:返回字符串的长度(字符个数)。
    • 用法size_t length() const;size_t size() const; 二者功能相同。
    • 代码示例
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    std::cout << "Length: " << str.length() << std::endl; 
    std::cout << "Size: " << str.size() << std::endl; 
    return 0;
}