String[] 去除空字符串
时间: 2023-10-07 11:11:07 浏览: 66
可以使用 Java 中的 Stream API 和 filter() 方法来实现。具体代码如下:
```java
String[] strArr = {"hello", "", "world", "", "java"};
String[] result = Arrays.stream(strArr)
.filter(str -> str != null && str.trim().length() > 0)
.toArray(String[]::new);
```
以上代码中,先使用 Arrays.stream() 方法将 String 数组转换成 Stream,然后使用 filter() 方法过滤掉空字符串(包括 null 和空格),最后使用 toArray() 方法将过滤后的字符串转换成 String 数组。
相关问题
string去掉特定字符串
你可以使用字符串的replace()方法来去掉特定的子字符串。下面是一个示例代码:
```python
def remove_string(original_string, target_string):
result = original_string.replace(target_string, '')
return result
# 示例用法
original_string = "Hello, World!"
target_string = "o"
result = remove_string(original_string, target_string)
print(result)
```
输出结果为: "Hell, Wrld!"
在这个示例中,我们定义了一个名为remove_string的函数,它接受两个参数:original_string表示原始字符串,target_string表示要去掉的特定字符串。函数内部使用replace()方法将目标字符串替换为空字符串,然后返回删除特定字符串后的结果。
String去除空字符
可以使用trim()方法去除字符串两端的空字符,也可以使用replace()方法去除字符串中的空字符。
示例:
```python
# 使用trim()方法去除字符串两端的空字符
s = " hello world "
s = s.strip()
print(s) # 输出:hello world
# 使用replace()方法去除字符串中的空字符
s = "hello world"
s = s.replace(" ", "")
print(s) # 输出:helloworld
```
注意:trim()方法只能去除字符串两端的空字符,如果想去除字符串中间的空字符,需要使用replace()方法。
相关推荐
![](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)