从一个字符串数组{"found" ,"the","sub", "string", "from", "hello", "world", "in", "java!"} 查找单词string
时间: 2023-09-05 20:08:41 浏览: 29
答案是:可以使用字符串的indexOf()方法,返回该单词在字符串中出现的下标位置。代码如下:
```
String[] arr = {"found" ,"the","sub", "string", "from", "hello", "world", "in", "java!"};
String keyword = "string";
int index = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(keyword)) {
index = i;
break;
}
}
if (index != -1) {
System.out.println("单词 " + keyword + " 在数组中的下标位置为 " + index);
} else {
System.out.println("数组中未找到单词 " + keyword);
}
```
相关问题
c++从一个字符串中查找另一个字符串的代码是什么
可以使用字符串类的 find 函数来查找一个字符串在另一个字符串中的位置,其函数原型为:
```cpp
size_t find (const string& str, size_t pos = 0) const noexcept;
```
其中第一个参数为要查找的字符串,第二个参数为起始查找位置,默认从字符串的开头开始查找。函数返回值为找到的子字符串的位置,如果找不到则返回 string::npos。
例如,假设要在字符串 `str` 中查找子字符串 `sub_str`,可以使用如下代码:
```cpp
#include <string>
std::string str = "hello world";
std::string sub_str = "world";
size_t pos = str.find(sub_str);
if (pos != std::string::npos) {
std::cout << "Found at position " << pos << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
```
此代码会输出 `Found at position 6`,表示子字符串 `sub_str` 在字符串 `str` 中的位置为 6。
std::string 字符串查找从最后开始
你可以使用 std::string 类型的 rfind() 函数来从字符串的末尾开始查找子字符串。rfind() 函数返回子字符串在字符串中最后一次出现的位置,如果找不到则返回 std::string::npos。
下面是一个示例代码:
```c++
#include <iostream>
#include <string>
int main()
{
std::string str = "Hello, world!";
std::string sub_str = "l";
size_t found = str.rfind(sub_str);
if (found != std::string::npos)
{
std::cout << "Substring found at position: " << found << std::endl;
}
else
{
std::cout << "Substring not found." << std::endl;
}
return 0;
}
```
输出结果:
```
Substring found at position: 10
```
在上面的代码中,我们使用 rfind() 函数查找子字符串从末尾开始的位置。如果子字符串存在,则打印其位置,否则打印“Substring not found.”。