-2

`

class GfG{
public String multiply(String a,String b){
        String s = "0.0.0.0";
        String[] str = s.split("\\.");
        for(String p:str){
            System.out.println(p);
        }
        return "";
    }
}

` I am splitting "0.0.0.0" and "0.0.0.0.". In both the cases i m getting same array of strings i.e 4 "0" strings. Can someone explain how this split is working for the two above cases.

2 Answers2

2

The reason that you are not receiving the empty string that you think should have been returned at the end is by design in split.

From the docs:

public String[] split(String regex)

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array

The important part of this is that Trailing empty string are therefore not included.

Reference: Official documentation

Martin
  • 16,093
  • 1
  • 29
  • 48
1

It appears that you ran the following

jshell> "0.0.0.0".split("\\.")
$1 ==> String[4] { "0", "0", "0", "0" }

jshell> "0.0.0.0.".split("\\.")
$2 ==> String[4] { "0", "0", "0", "0" }

and you are happy with the first result but you are wondering why the last result is not

String[4] { "0", "0", "0", "0", "" }

This is a good question to ask because if the dot was at the beginning of the string you would get the empty string!

jshell> ".0.0.0.0".split("\\.")
$3 ==> String[5] { "", "0", "0", "0", "0" }

This is just how split works. If there is a delimiter at the end of the string, no empty string is returned.

Duplicate of Java String split removed empty values, where it is explained in detail.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232