Hirthas
Hirthas

Reputation: 359

String.replace() is not working

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.

Upvotes: 3

Views: 1137

Answers (4)

nsgulliver
nsgulliver

Reputation: 12671

you should add back slash \ something like this

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

because one left slash \ is escape character

Upvotes: 1

user
user

Reputation: 3088

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 '

Upvotes: 9

James Oravec
James Oravec

Reputation: 20391

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

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499800

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.

Upvotes: 6

Related Questions