Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if the string in the Java split is not found

Tags:

java

string

split

    String incomingNumbers[ ] = writtenNumber.split("\\-"); 

The program accepts natural language numbers such as thirty-two or five.
So if five is entered, what lands in my incomingNumbers array?

like image 238
Armando Moncada Avatar asked Aug 02 '12 03:08

Armando Moncada


People also ask

What does split return if character not found?

split (separator, limit) , if the separator is not in the string, it returns a one-element array with the original string in it.

What happens when split empty string?

Using split() If the string and separator are both empty strings, an empty array is returned.

Why split is not working for dot in Java?

backslash-dot is invalid because Java doesn't need to escape the dot. You've got to escape the escape character to get it as far as the regex which is used to split the string.

What happens when you split a string in Java?

The string split() method breaks a given string around matches of the given regular expression. After splitting against the given regular expression, this method returns a string array.


1 Answers

You get an array of size 1 holding the original value:

Input       Output -----       ------ thirty-two  {"thirty", "two"} five        {"five"} 

You can see this in action in the following program:

class Test {     static void checkResult (String input) {         String [] arr = input.split ("\\-");         System.out.println ("Input   : '" + input + "'");         System.out.println ("    Size: " + arr.length);         for (int i = 0; i < arr.length; i++)             System.out.println ("    Val : '" + arr[i] + "'");         System.out.println();     }      public static void main(String[] args) {         checkResult ("thirty-two");         checkResult ("five");     } } 

which outputs:

Input   : 'thirty-two'     Size: 2     Val : 'thirty'     Val : 'two'  Input   : 'five'     Size: 1     Val : 'five' 
like image 63
paxdiablo Avatar answered Sep 30 '22 20:09

paxdiablo