2

I can't get what I'm missing here. Both replace and replaceAll from java.lang.String are generating a question mark (?) after each ocurrence:

        String str = "ABCD DKABCED DLS ABC";        
        System.out.println("str='"+str+"'");
        System.out.println("str.replaceAll(\"ABC\", \"A\\\\${BC}​\" ) => " + str.replaceAll("ABC", "A\\${BC}​" ));
        System.out.println("str.replace(\"ABC\", \"A${BC}​\" ) => " + str.replace("ABC", "A${BC}​" ));

Generates the following output:

str='ABCD DKABCED DLS ABC'
str.replaceAll("ABC", "A\\${BC}?" ) => A${BC}?D DKA${BC}?ED DLS A${BC}?
str.replace("ABC", "A${BC}?" ) => A${BC}?D DKA${BC}?ED DLS A${BC}?

Here an image of the execution: enter image description here

Does anybody knows why?

EDITED:

Just for the record. The problem it that there really WAS a character after the brackets. After coping and pasting to Notepad++ I could see the }?"text. Not in Netbeans. So purelly enconding missunderstanding.

3
  • You've totally changed the code in the question. The output no longer matches the code. Commented Feb 17, 2015 at 22:52
  • What happens when you remove $? Commented Feb 17, 2015 at 23:08
  • Nothing, the problem is with the } character. Commented Feb 17, 2015 at 23:08

2 Answers 2

2

I suspect this is a character encoding problem. When I pasted your code into Eclipse (on Windows) it could not save the code, complaining about the character set:

Some characters cannot be mapped using "Cp1252" character encoding.

When I retyped it in from scratch, the problem went away:

String str = "ABCD DKABCED DLS ABC";
System.out.println("str='" + str + "'");
System.out.println(str.replace("ABC", "A${BC}"));

produces the following (without extra ? marks):

str='ABCD DKABCED DLS ABC'
A${BC}D DKA${BC}ED DLS A${BC}

If you take the hexdump of a normal } you get 7d.

But for the } character in your code, I get 7d e2 80 8b

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

1 Comment

That is it! I copied the String I wanted to replace from an e-mail, I couldn't see that there was an invisible character. After copying and pasting it to Notepad++ I found it. Was driving me crazy xD Thanks anyway. Sorry for the meaningless question.
0

That would be because you have question marks in your replacement string. Thus replace and replaceAll are simply doing exactly what you are telling them to do.

2 Comments

What?? just realized the System.out.println also generated a question mark!! Look at the code, there is no question mark there!
It does not generate a question mark on my machine. Ensure that you saved your foreign characters as UTF-8 encoding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.