Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split not working correctly

Tags:

java

split

I am trying to save the groups in a string to an array so that I can use them in individual variables if I need to. For this I use split but for some reason I only get the full string in the first position in the array: ultimate_array[0]. If I want to use ultimate_array[1] I get an exception like "out of bounds". Do you have any idea what am I doing wrong?

String string_final = "";
String[] ultimate_array = new String[100];
String sNrFact = "";

string_final="Nrfact#$idfact1#$valfact1#$idfact2#$valfact2#$idfact3#$valfact3#$idfact4#$valfact4#$idfact5#$valfact5#$idfact6#$valfact6#$idfact7#$valfact7#$idfact8#$valfact8#$idfact9#$valfact9#$idfact10#$valfact10";

ultimate_array = string_final.split("#$");
sNrFact = ultimate_array[0];
like image 277
Berbec Dani Avatar asked Sep 10 '12 05:09

Berbec Dani


People also ask

Why is my split function not working?

The SPLIT function belongs to VBA. It isn't part of Excel because it returns an array. Spreadsheets show elements of arrays in different cells. Therefore the result of the SPLIT function can't be shown in a single cell which, Excel being unable to display the result, would render the function itself useless.

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.

How does the split function work?

The split() function works by scanning the given string or line based on the separator passed as the parameter to the split() function. In case the separator is not passed as a parameter to the split() function, the white spaces in the given string or line are considered as the separator by the split() function.


2 Answers

The split takes an regular expression and $ is a special character (end of string) so you have to escape it with backslash \. Anyway it is also special character, this time in Java, so you have to escape it also. The final code is:

ultimate_array = string_final.split("#\\$");
like image 173
Gaim Avatar answered Sep 22 '22 05:09

Gaim


You need to escape $ (end of string)

ultimate_array = string_final.split("#\\$");
like image 34
John Woo Avatar answered Sep 25 '22 05:09

John Woo