index 函数在 C++ 字符串处理中主要有以下应用:
查找子字符串:使用 index 函数可以查找一个字符串是否包含另一个子字符串,以及子字符串的位置。例如:
#include <iostream>
#include <cstring>
int main() {
const char* str = "Hello, World!";
const char* subStr = "World";
size_t pos = std::string(str).find(subStr);
if (pos != std::string::npos) {
std::cout << "子字符串 \"" << subStr << "\" 在字符串 \"" << str << "\" 中的位置是: " << pos << std::endl;
} else {
std::cout << "子字符串 \"" << subStr << "\" 不在字符串 \"" << str << "\" 中" << std::endl;
}
return 0;
}
在这个示例中,std::string(str).find(subStr) 将查找 str 中是否包含 subStr,并返回其位置(从 0 开始)。如果未找到子字符串,则返回 std::string::npos。
提取子字符串:通过 index 函数可以从一个字符串中提取子字符串。例如:
#include <iostream>
#include <cstring>
int main() {
const char* str = "Hello, World!";
const char* subStr = "World";
size_t pos = std::string(str).find(subStr);
if (pos != std::string::npos) {
std::string extracted = str + pos;
std::cout << "提取的子字符串 \"" << extracted << "\"" << std::endl;
} else {
std::cout << "未找到子字符串 \"" << subStr << "\"" << std::endl;
}
return 0;
}
在这个示例中,如果找到了子字符串 subStr,则通过 str + pos 计算子字符串的起始位置,并使用 std::string 构造函数创建一个新的子字符串。