数组中查找包含某些字符串
时间: 2023-07-09 08:30:27 浏览: 55
你可以使用循环遍历数组中的每个字符串,然后使用字符串的 contains() 方法来判断该字符串是否包含你要查找的子字符串。以下是一个示例代码:
```java
public static List<String> findStrings(String[] arr, String substring) {
List<String> resultList = new ArrayList<>();
for (String str : arr) {
if (str.contains(substring)) {
resultList.add(str);
}
}
return resultList;
}
```
该方法接收一个字符串数组和一个子字符串作为参数,返回一个包含所有包含子字符串的字符串的列表。
相关问题
strstr 字符串数组中包含0x00
`strstr` 函数在遇到字符串数组中的 `0x00` 时会停止搜索,因为 `0x00` 是字符串的结束符。如果字符串数组中包含 `0x00`,则不能使用 `strstr` 函数进行搜索。
一种解决方法是使用 `memmem` 函数,该函数用于在内存块中搜索指定的子内存块。函数原型如下:
```c
void *memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen);
```
其中,`haystack` 为要搜索的内存块,`haystacklen` 为要搜索的内存块的长度,`needle` 为要查找的子内存块,`needlelen` 为要查找的子内存块的长度。函数返回值为指向第一次出现子内存块的指针,如果未找到则返回 `NULL`。
示例代码如下:
```c
byte data[6] = {0x12, 0x34, 0x00, 0x56, 0x78, 0x00}; // 待搜索的字符串数组
byte pattern[3] = {0x00, 0x56, 0x78}; // 要查找的子字符串数组
byte *ptr = (byte *)memmem(data, sizeof(data), pattern, sizeof(pattern)); // 在字符串数组中搜索子字符串数组
if (ptr != NULL) {
int position = ptr - data; // 计算子字符串在字符串数组中的位置
Serial.println(position);
} else {
Serial.println("not found");
}
```
在上面的示例代码中,`memmem` 函数的第一个参数 `data` 是要搜索的字符串数组,第二个参数 `sizeof(data)` 是要搜索的字符串数组的长度,第三个参数 `pattern` 是要查找的子字符串数组,第四个参数 `sizeof(pattern)` 是要查找的子字符串数组的长度。使用上面的代码示例,串口输出的内容为 `2`,表示子字符串在字符串数组中的位置为 2。
注意:`memmem` 函数在某些编译器中可能不可用,需要包含相应的头文件才能使用。例如,在 Arduino 中可以包含 `string.h` 头文件来使用 `memmem` 函数。
matlab 字符串字符数组
在MATLAB中,字符串是一种数据类型,表示为一系列字符数组。MATLAB中的字符串可以包含字母、数字、符号和空格等字符。字符串类型在MATLAB中的常用操作包括连接、分割、查找、替换、转换等。
字符数组是另一种数据类型,表示为一个字符矩阵。字符数组在MATLAB中也可以包含字母、数字、符号和空格等字符。在MATLAB中,可以使用单引号来定义字符数组,如'hello'。字符数组的常用操作包括连接、分割、索引、切片等。
需要注意的是,字符串和字符数组虽然在某些情况下可以互换使用,但它们在内部存储和处理方式不同,因此在使用时需要注意类型转换。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)