3

What I have is a string array that I am creating from a .csv file I am reading. I then want to parse the values I'm going to use for the ' character and replace it with a \' because I am outputting this to a javascript file.

Here's the code I'm using for that:

while ((thisLine = myInput.readLine()) != null) { String[] line = thisLine.split("\t"); if(line[4].indexOf("'") > -1){ System.out.println(line[4]); line[4] = line[4].replace("'", "\'"); System.out.println(line[4]); } brand.add(line[4]); } 

However this is not working. I am getting the same string back after I do the replace.

Is this because of some issue with the string array?

I appreciate any assistance in this matter.

1
  • 2
    Java escapes the backslash char too. Use "\\'". Commented Feb 21, 2013 at 15:54

4 Answers 4

9

Try like this:

line[4] = line[4].replace("'", "\\'"); 

The backslash must be "escaped".

In case of line[4] = line[4].replace("'", "\'"); the part \' is converted to just '

Sign up to request clarification or add additional context in comments.

1 Comment

You are not dumb. Never call yourself such way, the thoughts are material. We all have a field to study any time.
6

You're falling foul of the fact that "'" is the same as "\'". They're the same string (a single character, just an apostrophe) - the escaping is there to allow a character literal of '\''.

You want:

line[4] = line[4].replace("'", "\\'"); 

So now you're escaping the backslash, instead of the apostrophe. So you're replacing apostrophe with backslash-then-apostrophe, which is what you wanted.

See JLS section 3.10.6 for details of escaping in character and string literals.

Comments

1

you should add back slash \ something like this

line[4] = line[4].replace("'", "\\'"); 

because one left slash \ is escape character

Comments

0

Your issue looks like it is an escape issue. Try \\ to replace a single back slash.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.