如何将包含字符转义序列的字符串转换为字符? [英] How can I convert a string containing a character escape sequence into a char?
问题描述
我正在寻找一种方法来将包含字符转义序列的字符串转换为表示的字符。
I'm looking for a way to convert a string that contains a character escape sequence into the represented character.
例如,我想解析字符串 \
(其中有两个字符,一个反斜杠和一个双引号)插入到char 。
So, for instance, I want to parse the string \"
(which has two characters, a backslash and a double-quote) into the char "
. So, an array of chars into one char.
所以,可能会做这样的事情,反之亦然:
So something that might do something like this and vice versa:
package test;
public class Test {
private static char parseChar(String string) {
char c = 0;
if ("\\n".equals(string)) {
c = '\n';
}else if ("\\t".equals(string)) {
c = '\t';
}else if ("\\r".equals(string)) {
c = '\r';
}else if ("\\f".equals(string)) {
c = '\f';
}else if ("\\b".equals(string)) {
c = '\b';
}else if ("\\\'".equals(string)) {
c = '\'';
}else if ("\\\"".equals(string)) {
c = '\"';
}else if ("\\\\".equals(string)) {
c = '\\';
}
return c;
}
public static void main(String[] args) {
for (String arg : args) {
System.out.println(arg + " : " + (int)parseChar(arg) + " : " + parseChar(arg) + ";");
}
}
}
我不敢相信java.lang或其他可以为我提供良好(也许本机)代码为此,因为我觉得上述代码可能不完整,不解析每个有问题的(可脱机?)字符,因为我是一个noob。
我想要一个工具,可以做与String构造函数相同的工作:
I could not believe there is nothing in java.lang or other that can provide me with good (maybe native) code for this because I feel the above code might be incomplete and not parse every problematic (escapable?) character, because well I'm a noob. I want a tool that can do the same thing as the String constructor :
String st = "\"";
char ch = st.charAt(0);
ch输出:;
ch output : ";
感谢您阅读,对不起,如果不清楚我会定期检查, 。
Thank you for reading this, I am sorry if not clear I will check regularly and correct if asked.
PS :
当我运行上述代码时:
java -classpath〜/ workspace / MacroRecorder / bin / test.Test \\\\
\\t \\f \ \r \\b \\\'\\\\\\\;
java -classpath ~/workspace/MacroRecorder/bin/ test.Test \\n \\t \\f \\r \\b \\\' \\\" \\\\;
...它输出
\n : 10 :
;
\t : 9 : ;
\f : 12 :
;
;r : 13 :
\b : 8 :;
\' : 39 : ';
\" : 34 : ";
\\ : 92 : \;
但在Eclipse中,输出与相同的参数完全不同,特别是非常混乱。
But in Eclipse, the output is completely different with the same parameters especially the " is very messy.
推荐答案
Apache Commons用StringEscapeUtils解救,你想要的unescapeJava方法我想: http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/StringEscapeUtils.html#unescapeJava(java.lang.String )
Apache Commons to the rescue with StringEscapeUtils, you want the unescapeJava method I think: http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/StringEscapeUtils.html#unescapeJava(java.lang.String)
这篇关于如何将包含字符转义序列的字符串转换为字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!