0

I want to parse this CSV String:

DEV-82,2d155089e1b01eb,AYNF Terminal 2,ENABLED,PAN_FZN1_AD5,SIT-4,MetesCronos,DGP-83,AllYouNeedFresh,20170902042148,356927070012616,!,!

And write out a CSV in JAVA:

2d155089e1b01eb,SIT-4,MetesCronos,356927070012616

Is there any ways to take n-th positions from strings?


However my string is not consists just one line, It some times 50 lines, sometimes 75 lines etc.

My Stringresult is:

DEV-1,77EC0067C8A1BA6462FCA25F8B1DFBE289F6A3EE,6110 WM,DISABLED,HON_6110_WM6,SIT-3,letesena,DGP-1,6110WM,,,,
DEV-2,01B406234550B1A688000050BF7A60E2,MC3090 CE,DISABLED,MOT_MC3000_CE50,SIT-3,Letesena,DGP-2,MC3090,,,,
DEV-37,23B8EB959C4004D373EAB6A9ACA7173DE15266F1,MC67 AlexH,ENABLED,MOT_MC67_WM6,SIT-4,Letesonos,DGP-32,MCL-Client_MC67,20170915220217,352344052521784,!,!
DEV-45 ...

And I want to take each line 2nd, 5th, and 11th columns and write a CSV:

77EC0067C8A1BA6462FCA25F8B1DFBE289F6A3EE,SIT-3,6110WM
01B406234550B1A688000050BF7A60E2,SIT-3,MC3090
23B8EB959C4004D373EAB6A9ACA7173DE15266F1,SIT-4,MCL-Client_MC67 
phflack
  • 2,729
  • 1
  • 9
  • 21
  • It's easier to parse an array of strings, but if you've already put them into one large string you can use `String[] lines = Stringresult.split("\n");` to split it back into lines, before using `String[] values = lines.split(",");` in a loop, getting the values you want with `String out = values[1] + "," + values[4] + "," + values[10];` and writing out the result – phflack Feb 15 '18 at 16:44
  • 1
    Possible duplicate of [How to split a string in Java](https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – phflack Feb 15 '18 at 16:46

2 Answers2

1

Use String.split(separator), then take the nth entry from the resulting array.

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

Andreas Hartmann
  • 1,825
  • 4
  • 23
  • 36
0

Either using String.split(",") and then getting the n-th from the result array, or better use a tool, which is already handling a lot of corner-cases (e.g., not enough parts in the CSV-row; UTF-8 BOMs) for you. Such a tool is for example Commons CSV.

D. Kovács
  • 1,232
  • 13
  • 25