Berbec Dani
Berbec Dani

Reputation: 53

split not working correctly

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];

Upvotes: 5

Views: 166

Answers (4)

Paritosh Soni
Paritosh Soni

Reputation: 21

Just replace your line:

ultimate_array = string_final.split("#$"); 

with:

ultimate_array = string_final.Split(new string[] { "#$" }, StringSplitOptions.None);

I hope your problem is resolved...

Upvotes: 0

Grisha Weintraub
Grisha Weintraub

Reputation: 7986

ultimate_array = string_final.split("#\\$");

The reason your split is not working correctly is that split uses regex and "$" is a special character for regexes(drekka)

Upvotes: 2

John Woo
John Woo

Reputation: 263723

You need to escape $ (end of string)

ultimate_array = string_final.split("#\\$");

Upvotes: 2

Gaim
Gaim

Reputation: 6844

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("#\\$");

Upvotes: 3

Related Questions