In an Android app I'm making, I construct a TextView
programmatically and pass a String
to setText
. The String I'm passing is obtained from another source, and it contains escape characters. Here's an example String:
AxnZt_35\/435\/46\/34
The \\/
should in fact be just /
. But the TextView
displays the whole thing exactly as in the above example.
The code I'm using to construct the TextView
:
TextView textView = new TextView(context);
textView.setText(text);
textView.setTextColor(color);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setTextSize(14);
So my question is, how can I not display the extra \\
? I just want the above example displayed as:
AxnZt_35/435/46/34
Thanks.
EDIT
The String I provided above is just an example. There might be other characters in the String. For example, the character /
or \\
by itself is perfectly valid. The problem is that /
is displayed as \\/
.
The answer from @Numan1617 is close, but for escape characters and replaceAll()
, you have to escape them twice.
See This Post .
So, the correct code in this case would be:
String str = "AxnZt_35\\/435\\/46\\/34";
System.out.println(str); //prints AxnZt_35\/435\/46\/34
String s2 = str.replaceAll("\\\\/", "/");
System.out.println(s2); //prints AxnZt_35/435/46/34
您必须使用Strings replaceAll方法设置文本之前,替换所有\\的出现:
textView.setText(text.replaceAll("\\", ""));
Run this as plain Java
public class Klass{
public static void main(String[] args) {
System.out.println(new String("\\/"));
System.out.println(new String("\\/").replaceAll("/", ""));
System.out.println(new String("\\/").replaceAll("\\/", ""));
System.out.println(new String("\\/").replaceAll("\\\\/", ""));
}
}
The regex for \\ is "\\\\": in regex one pair of \\ is equal to one \\ in the new String()
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.