Java Replacing all commas with semi-colons except the ones inside quotations marks

StackOverflow https://stackoverflow.com/questions/22620079

  •  20-06-2023
  •  | 
  •  

문제

Replacing all commas except the ones inside quotations marks in java with CSV style user input.

I've done some research but can't wrap my head around how/where to start to do this, not sure if I can ask questions without adding any code but, if anyone could help me by suggesting functions to use/research to do this I would really appreciate it

p.s I've seen a few other posts but from what I read it wasn't working properly.

도움이 되었습니까?

해결책

2 suggestions:

  1. Use a CSV parsing library like commons-csv to tokenize the input and then re-join it with whichever character you want. CSV libraries are smart enough not to split on commas within quotes.
  2. Implement a finite state machine (2 states: within quotes and outside quotes) to scan the input keeping track of whether or not the current character is inside quotes. When you find a comma and you're not inside quotes, replace it.

다른 팁

Here is some pseudocode:

Read character
if character is ','
   replace with ';'
else if character is '"'
   read character until it is '"'
else
   do nothing
Repeat

How about writing your own parser which would work like

set flag which checks if we are inside quotation to false
create buffer for changed version of original string (StringBuilder )

for (each character in string)
    if (character is comma and is inside quotation)
        add semicolon to StringBuilder
    else
        add character to StringBuilder
        if (character is quotation mark)
            reverse quotation flag

when you are done with iterating over characters get content of StringBuilder
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top