有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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 ]等于什么,这个问题就解决了。 当我将元素复制到一个新数组中时,知道这个值会给我一些可以比较的东西


共 (2) 个答案

  1. # 1 楼答案

    这是我的解决方案。跳过empty" "字符串,并将notEmpty values附加到new StringBuilder()上,最后打印出来

    import java.util.Arrays;
    
    public class LOL_problem {
    
    public static void main(String[] args) {
            String trollText = "MakeLOLLOLLOLMELOLALOLSandWich";
            StringBuilder sb = new StringBuilder();
            String[] array = trollText.split("LOL");
            //System.out.println(Arrays.toString(array));
    
            for (String str : array) {
                if (!str.equals("")) sb.append(str+" ");
            }
            System.out.println(sb.toString().trim());
        }
    }
    
  2. # 2 楼答案

    在java中比较两个字符串时,不能使用==运算符来比较对象引用。你需要使用array[1].equals("")

    此外,如果您只是想替换字符串的所有匹配项,可以执行以下操作

    trollText.replaceAll("LOL", " ")