C++ indexOf
时间: 2023-08-16 14:15:12 浏览: 234
在 C++ 中,没有直接提供类似于 JavaScript 中的 `indexOf` 函数来查找字符串中某个子字符串的位置。但是,你可以使用 `std::string` 类的成员函数 `find` 来实现类似的功能。这个函数会返回子字符串在主字符串中第一次出现的位置,如果找不到则返回 `std::string::npos`。
下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello world!";
std::string subStr = "world";
size_t pos = str.find(subStr);
if (pos != std::string::npos) {
std::cout << "Substring found at position: " << pos << std::endl;
} else {
std::cout << "Substring not found." << std::endl;
}
return 0;
}
```
输出结果为:
```
Substring found at position: 6
```
这里的 `find` 函数会返回子字符串 "world" 在主字符串 "Hello world!" 中的位置 6。如果子字符串不存在,则返回 `std::string::npos`。
相关问题
C++ indexof
在 C++ 中,没有直接的内置函数叫做 `indexOf`。不过,你可以使用 `std::string` 类型的成员函数 `find` 来查找一个子字符串在另一个字符串中的位置。下面是一个示例:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
std::string subStr = "world";
// 使用 find 函数查找子字符串的位置
size_t pos = str.find(subStr);
if (pos != std::string::npos) {
std::cout << "子字符串的位置: " << pos << std::endl;
} else {
std::cout << "未找到子字符串" << std::endl;
}
return 0;
}
```
这个示例中,我们定义了一个字符串 `str` 和一个子字符串 `subStr`。然后,我们使用 `str.find(subStr)` 来查找子字符串在字符串中的位置,并将结果存储在变量 `pos` 中。如果子字符串存在,`pos` 将返回子字符串在字符串中的起始位置;否则,它将返回 `std::string::npos`。
上述代码将打印出子字符串 "world" 在字符串 "Hello, world!" 中的位置,即 7。如果子字符串不存在,它将打印出 "未找到子字符串"。
c++ indexOf
在C语言中,并没有直接对应于Java的indexOf函数的函数名为indexOf的函数。不过在C语言中,可以使用字符串处理函数find或者find_first_of来实现类似的功能。
find函数在C++中是一个成员函数,可以用于查找字符串中第一次出现指定字符或字符串的位置。
find_first_of函数也是一个成员函数,用于在字符串中查找任意字符中的任意字符的位置。
所以在C语言中,可以使用find或者find_first_of函数来实现类似于Java中indexOf函数的功能。
阅读全文
相关推荐















