c++

C++ npos面试题精选解析

小樊
85
2024-07-14 10:10:30
栏目: 编程语言

  1. 什么是npos?

npos是string类中的一个静态成员变量,表示一个不存在的位置或者不存在的索引。在大多数情况下,当字符串中的一个函数返回npos时,表示没有找到指定的字符串或者字符。

  1. npos的值是多少?

npos的值通常是一个非常大的数值,通常等于-1(unsigned类型)。在C++中,npos定义为一个constexpr值,其实际值是std::string::npos。

  1. 如何判断字符串中是否包含指定的子字符串?

可以使用string类的find()函数来判断字符串中是否包含指定的子字符串。如果find()函数返回值等于npos,表示没有找到指定的子字符串。

例如:

std::string str = "Hello, World!";
if(str.find("World") != std::string::npos) {
    std::cout << "Found!" << std::endl;
} else {
    std::cout << "Not Found!" << std::endl;
}
  1. 如何用npos删除字符串中的所有字符?

可以使用string类的erase()函数来删除字符串中的所有字符。将erase函数的参数设为0和string::npos即可删除所有字符。

例如:

std::string str = "Hello, World!";
str.erase(0, std::string::npos);
std::cout << str << std::endl; // Output: ""
  1. 如何用npos替换字符串中的所有字符?

可以使用string类的replace()函数来替换字符串中的所有字符。将replace函数的参数设为0和string::npos即可替换所有字符。

例如:

std::string str = "Hello, World!";
str.replace(0, std::string::npos, "Goodbye!");
std::cout << str << std::endl; // Output: "Goodbye!"

0
看了该问题的人还看了