Gil Platt
Gil Platt

Reputation: 41

Replacing apostrophes in a Java string with a " \' "

I am currently working on a project that involves using Weka to classify headlines based on their crime type. Since Weka uses .arff files, any headline with an apostrophe in it must be escaped.

List<String> headlines = demoPipe.getHeadlines();
    for (int i = 0; i < headlines.size(); i++) {

        if(headlines.get(i).contains("'"))
            headlines.get(i).replace("'", "\\'");

        System.out.println(headlines.get(i));

        //System.out.printf("'%s'%n", headline);
    }

The if statement is where I'm trying to escape the apostrophes, however when I print out the headlines, any headlines with apostrophes remain unchanged. How can I fix this issue?

Upvotes: 2

Views: 648

Answers (2)

Hasnain Bukhari
Hasnain Bukhari

Reputation: 468

I think it won't replace like you are doing. Few days ago same problem I was facing. You have to assign it to make it useful.

List<String> headlines = demoPipe.getHeadlines();
    for (int i = 0; i < headlines.size(); i++) {

        if(headlines.get(i).contains("'"))
            headlines.set(i,headlines.get(i).replace("'", "\'"));

        System.out.println(headlines.get(i));

        //System.out.printf("'%s'%n", headline);
    }

Try like this it will work for you.

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56453

strings are immutable, meaning any modification to a string yields a new string with the new modifications and leaves the previous string unchanged.

headlines.get(i).replace("'", "\\'");

The above replace operation is returning a new string object with the new modifications but you're ignoring it.

So, to overcome the problem you'll need to utilise the set method of the List<T> and assign back the new string.

headlines.set(i,headlines.get(i).replace("'", "\\'"));

Further, you can simplify the replacing logic with the replaceAll method as of JDK-8:

headlines.replaceAll(s -> s.contains("'") ? s.replace("'", "\\'") : s);

if for whatever reason, you don't want to modify the source list then you can collect the results to a new list as follows:

List<String> result = 
       headlines.stream()
                .map(s -> s.contains("'") ? s.replace("'", "\\'") : s)
                .collect(Collectors.toCollection(ArrayList::new));

or you can print directly to the console without constructing a new list:

headlines.stream()
         .map(s -> s.contains("'") ? s.replace("'", "\\'") : s)
         .forEach(System.out::println);

Upvotes: 3

Related Questions