0

I read from a text file and sometimes I get in a string something like:

;onor Oyj,Native,Uor Oyj1,"Uponor Oyj, UBS, Innovation AB",39639d4d26:-21f7;

I need to split the string like this:

'onor Oyj',  
'Native',  
'Uor Oyj1',  
'Uponor Oyj, UBS, Innovation AB',  
'39639d4d26:-21f7',  
';'

How can I do this?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
coco
  • 95
  • 1
  • 8

1 Answers1

1

Something like:

  String str = ";onor Oyj,Native,Uor Oyj1,\"Uponor Oyj, UBS, Innovation AB\",39639d4d26:-21f7;";
  char[] c = str.toCharArray();
  boolean inQuote = false;
  for (int i = 0; i < c.length; i++)
  {
     if (c[i] == ',' && !inQuote)
        c[i] = '\01'; // some value that doesn't appear in the string
     if (c[i] == '"')
        inQuote = !inQuote;
  }
  String[] arr2 = String.valueOf(c).split("\\01");
  for (String s: arr2)
  {
     System.out.println(s);
  }

Outputs:

;onor Oyj
Native
Uor Oyj1
"Uponor Oyj, UBS, Innovation AB"
39639d4d26:-21f7;

Replace String[] arr2 = String.valueOf(c).split("\\01"); with String[] arr2 = String.valueOf(c).replaceAll("\"", "").split("\\01"); to remove the quotes.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138