0

So I want to split this String

String s = "1,lastname,firstname,"1200,00$",address";

So the split char is ','

The problem now is that 00 is the address because it's splitting at ','

Is there a way how I can get 1200,00 into one.

This is how I split

String[] split = res.split(",");
arrlist.add(new Data(split[0], split[1], split[2], split[3], split[4]))

The result I get looks like this: ID: 1, LastName: lastname, FirstName: firstname, Salary: "1200, Address: 00$

Boken
  • 4,825
  • 10
  • 32
  • 42
id6070
  • 1
  • 1
  • 2
  • Can you just split on `, ` (with space) instead? – Nicolas May 08 '20 at 19:41
  • 1
    Just split the string using `" "` (space) character. Although, the string you posted is invalid. – Ervin Szilagyi May 08 '20 at 19:43
  • Actually, it looks like you have an invalid String alltogether. The string should start and end with double-quotes, so once the double-quote in from of "1200 is encountered the String is closed and everything after would be considered a compile error. If you want to have double -quoted within the contents of the String, they need to have an escape character \" – pczeus May 08 '20 at 19:43
  • It's not an invalid String I'm getting this String from a website so I can't add a space – id6070 May 08 '20 at 19:44
  • I think this post could help you : https://stackoverflow.com/questions/15738918/splitting-a-csv-file-with-quotes-as-text-delimiter-using-string-split – Tom May 08 '20 at 19:50
  • Quotes inside your String should be excaped : `String s = "1,lastname,firstname,\"1200,00$\",address";` – Tom May 08 '20 at 19:52
  • 2
    Does this answer your question? [Splitting on comma outside quotes](https://stackoverflow.com/questions/18893390/splitting-on-comma-outside-quotes) – Eritrean May 08 '20 at 19:52
  • 1
    Your string is NOT correct. Do you have `'` inside them? – Boken May 08 '20 at 19:54
  • 1
    If your string contains double-quoted values that themselves contain commas, then it is basically a one-line CSV file. I would use a real CSV parser such as the one from Apache Commons. You can play a lot of tricks with regular expressions and even get something working for *this* data, but you will inevitably have other problems unless this is just a simple test program or homework assignment. Regular expressions are not really the right tool to use, here. – David Conrad May 08 '20 at 20:12

1 Answers1

1

Input

When input is like there:

"1,lastname,firstname,1200,00$,address"

Split

so when yoy split it by , you receive:

output[0]  ->  1
output[1]  ->  lastname
output[2]  ->  firstname
output[3]  ->  1200
output[4]  ->  00$
output[5]  ->  address

so you can merge position 3 and 4 together.

New code

String amount = split[3] + "," + split[4];
arrlist.add(new Data(split[0], split[1], split[2], amount, split[5]));
Community
  • 1
  • 1
Boken
  • 4,825
  • 10
  • 32
  • 42