在右侧编辑器Begin-end处填充代码,实现在数组中查找指定字符串位置的功能。
时间: 2024-11-30 13:22:01 浏览: 103
要在数组中查找指定字符串的位置,你可以使用遍历数组的方式。假设我们有一个字符串数组和一个目标字符串,下面是一个简单的示例,展示了如何在C++中使用`std::string` 和 `find` 函数:
```cpp
#include <iostream>
#include <vector>
#include <string>
std::vector<std::string> array = {"apple", "banana", "cherry", "date"}; // 示例数组
std::string targetString = "banana"; // 指定的目标字符串
// 查找函数
size_t findPosition(const std::string& str, const std::vector<std::string>& arr) {
for (size_t i = 0; i < arr.size(); ++i) {
if (arr[i] == str) {
return i;
}
}
return -1; // 如果没有找到,则返回-1表示未找到
}
int main() {
size_t position = findPosition(targetString, array);
if (position != -1) {
std::cout << "Target string \"" << targetString << "\" found at position " << position << std::endl;
} else {
std::cout << "Target string not found in the array." << std::endl;
}
return 0;
}
```
在这个代码中,`findPosition` 函数遍历数组并使用 `==` 运算符检查每个元素是否等于目标字符串。如果找到匹配项,它将返回该元素的索引;如果没有找到,最后返回 `-1`。
阅读全文
相关推荐



















