-3

Suppose I have a given String like:

String s="\"Name\"=>\"Bruce, Wayne\", \"City\"=>\"Bangalore\", \"Country\"=>\"India\"";

Currently in my program I am splitting that string like this

String[] tokens=s.split(", ");

Now when i try to print tokens[0] the output is going to be

"Name"=>"Bruce

but I want my output to be

"Name"=>"Bruce, Wayne"

I know the reason why is it happening because of the way i am splitting it (", ") What changes should i make in my logic such that i dont have to change my splitter from a comma but again if the data has comma,the csv file should ignore it

Can someone help me with a general solution? The example used was just to make the question clear.

Sample Java Code FYR

class HelloWorld 
{
  public static void main(String[] args) 
  {
    String s="\"Name\"=>\"Bruce, Wayne\", \"City\"=>\"Gotham\", \"Country\"=>\"USA\"";
    String[] tokens=s.split(", ");
    System.out.println(tokens[0]);
  }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 4
    Find a library for processing CSV. You could write your own but you'll probably be better off with a proven library that already exists. If you did want to do it yourself, you need to walk the string, if you encounter a quote then you need to ignore commas until the next quote. Then you'll probably want to handle escaped quotation marks, see https://csv-spec.org/. – Paul Ruane Aug 25 '23 at 17:37

0 Answers0