String original = "This is my string valúe";
我想上面的字符串编码成UTF-8等价的,但只更换特殊字符(U) - “ú”在这种情况下。的Java编码特殊字符的字符串使用UTF-8字符
我使用下面的尝试,但我得到一个错误:
Input is not proper UTF-8, indicate encoding !Bytes: 0xFA 0x20 0x63 0x61
代码:
String original = "This is my string valúe";
我想上面的字符串编码成UTF-8等价的,但只更换特殊字符(U) - “ú”在这种情况下。的Java编码特殊字符的字符串使用UTF-8字符
我使用下面的尝试,但我得到一个错误:
Input is not proper UTF-8, indicate encoding !Bytes: 0xFA 0x20 0x63 0x61
代码:
你可以使用String.replace(CharSequence, CharSequence)
和格式化的IO喜欢
String original = "This is my string valúe";
System.out.printf("Output : %s%n", original.replace("ú", "ú"));
它输出(因为我认为你想要)
Output : This is my string valúe
如果我有另一个特殊字符如“ñ”,该怎么办?这些有没有一种方法可以将任何特殊字符转换为等效的UTF-8值? – user4015632
查看['StringEscapeUtils'](https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html)和'escapeHtml'。 –
StringEscapeUtils解决了这个问题! – user4015632
能否请您尝试以下线路:
byte ptext[] = original.getBytes("UTF8");
String value = new String(ptext, "UTF8");
我仍然得到这个 - >这是我的字符串valúe。期望的解决方案 - >这是我的字符串val ú e – user4015632
你似乎想用XML字符实体。
Appache Commons Lang有一个方法(在StringEscapeUtils中)。
Im trying to encode the above string to UTF-8 equivalent but to replace only >special character (ú) with -- "ú ;" in this case.
我不知道什么编码“ú”是,但你有没有试过看URLEncoder
课?它不会完全按照你问的方式对字符串进行编码,但它可以摆脱幽灵般的角色。
URLEncoder类使用全部+符号等对纯文本进行编码,这实际上并不奏效。但是StringEscapeUtils更适合Html页面文本或标题 – user4015632
@ user4015632为何投票 – user4015632
投票的原因是什么? – user4015632