Mouaz Tabboush
Mouaz Tabboush

Reputation: 25

Split method creates empty elements in Java Array

I have the following String "Make Me A SandWich" Someone decided to troll me and replace the spaces with a random number of LOL. so now the string is "LOLMakeLOLLOLLOLMELOLALOLSandWich"

My goal is to revert this change.

I tried to create a string array with split method but this caused "empty" elements inside of the array that has a value but when I try to log it, it doesn't show anything. It's also not equal to ""

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");
    }
}

I consider the problem solved if someone tells me what array[1] equals to. Knowing the value will give me something to compare to when copying the elements into a new array.

Upvotes: 0

Views: 96

Answers (4)

GitPhilter
GitPhilter

Reputation: 171

To compare Strings in Java, use:

String.equals("text");

This will return true if the Strings are identical and false if not.

Upvotes: 0

Dnyanesh
Dnyanesh

Reputation: 121

We should use equals(String str) method to check if strings are equals instead of '==' which does object reference check. To replace all the occurrence, you can use trollText.replaceAll method as below.

    public class MyClass{
      public static void main(String[] args) {
        String trollText = "MakeLOLLOLLOLMELOLALOLSandWich";
        String result  = trollText.replaceAll("LOL", " ");
        System.out.println(result);
    }
}

Upvotes: 0

A S M Sayem
A S M Sayem

Reputation: 2070

Here is my solution. skipping empty or " " string and appending notEmpty values to new StringBuilder() and finally print it.

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());
    }
}

Upvotes: 0

Bunyamin Coskuner
Bunyamin Coskuner

Reputation: 8859

When comparing two strings in java, you cannot use == operator which compares object references. You need to use array[1].equals("")

Also, if you simply want to replace all occurrences of a string, you can do following

trollText.replaceAll("LOL", " ")

Upvotes: 1

Related Questions