"/>
  简体   繁体   中英

Replacing (not removing) special char in a String by other char

I need to replace "《br》" to "<br>" .

replaceAll does not work, but if I do it in the variable window when debugging ... it works!

Same with indexOf("《") , returns -1 but using the variable window returns 12

How can I replace it?

这是我在调试时在变量窗口中看到的。代码中的相同内容不起作用。

这是我在代码中看到的(检查这个>:pos1 = -1)

So the question is, how to make it work in the code

As String is immutable you are not changing original value of text variable. replaceAll creates new String with correct value and you have to assign it to variable to use it.

Reference of usage can be found here with some more explanation, but basic usage is:

String originalText ="some text with letters to replace";  
String newTextWithReplacedValues = originalText.replaceAll("a","e");//replaces all occurrences of "a" to "e"  
System.out.println(newTextWithReplacedValues);  

You can see it working in the debugger since text.replaceAll(...) returns proper value. It is just not changing original text variable.

For me replacing just works fine.

public class Application {
    public static void main(String[] args) {
        String s = "《br》";
        s = s.replace("《", "<").replace("》", ">");
        System.out.println(s);
    }
}

《 may not be a single character though since '《' gives an error but "《" works.

This is the Character documentation:

The set of characters from U+0000 to U+FFFF is sometimes referred to as the Basic Multilingual Plane (BMP). Characters whose code points are greater than U+FFFF are called supplementary characters. The Java platform uses the UTF-16 representation in char arrays and in the String and StringBuffer classes. In this representation, supplementary characters are represented as a pair of char values, the first from the high-surrogates range, (\?-\?), the second from the low-surrogates range (\?-\?).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM