Split方法在Java数组中创建空元素
我有下面这句话“给我做个三明治” 有人决定用随机数LOL替换空格。 所以现在的字符串是“LolmakelollolmelolalolSandwich”
我的目标是恢复这种变化
我试图用split方法创建一个字符串数组,但这导致数组中有一个值的“空”元素,但当我尝试记录它时,它没有显示任何内容。它也不等于“
Public class MyClass{
public static void main(String[] args) {
String trollText = "MakeLOLLOLLOLMELOLALOLSandWich";
String[] array = trollText.split("LOL");
if (array[1]=="")System.out.print("it's an empty string");
if (array[1]==" ")System.out.print("it's a space sign");
if (array[1]==null)System.out.print("it's equal to nothing");
if (array[1]==' '+"")System.out.print("I don't know what's that");
else System.out.print(array[1]+"<-- This is an element and it has a value");
}
}
我认为如果有人告诉我数组[1 ]等于什么,这个问题就解决了。
当我将元素复制到一个新数组中时,知道这个值会给我一些可以比较的东西
# 1 楼答案
这是我的解决方案。跳过
empty
或" "
字符串,并将notEmpty values
附加到new StringBuilder()
上,最后打印出来# 2 楼答案
在java中比较两个字符串时,不能使用
==
运算符来比较对象引用。你需要使用array[1].equals("")
此外,如果您只是想替换字符串的所有匹配项,可以执行以下操作
trollText.replaceAll("LOL", " ")