我想转代表特殊字符的两个字符的字符串,例如“”,“ "," ",... 转换为单个字符表示形式。是否有任何通用方法可以做到这一点(通用,我的意思是显式将每个字符串翻译为每个字符的替代方法)?
理想的行为(我的字符串正在从文件中读取。这只是一个示例):
String str = "\\t";
char c = toChar(str); // c now represents the tab character '\t'
您可以直接使用转义序列,例如
"\t"
表示制表符、"\n"
表示换行符、"\a"
表示警报等,来表示特殊字符。无需使用自定义函数将它们转换为单个字符。
String str = "\t"; // This represents the tab character '\t'
System.out.println(str); // Outputs a tab
如果您有字符串
"\t"
并希望将其转换为制表符,您只需按原样使用它即可。
并且,就像 Nexevis 所说:
...它不需要是字符串。所以,这也有效:
char c = '\t'; // This represents the tab character '\t'
System.out.println(c); // Outputs a tab