如何将表示“特殊”字符的字符串转换为其字符表示形式

问题描述 投票:0回答:1

我想转代表特殊字符的两个字符的字符串,例如“”,“ "," ",... 转换为单个字符表示形式。是否有任何通用方法可以做到这一点(通用,我的意思是显式将每个字符串翻译为每个字符的替代方法)?

理想的行为(我的字符串正在从文件中读取。这只是一个示例):

String str = "\\t";
char c = toChar(str); // c now represents the tab character '\t'
java string char
1个回答
0
投票

您可以直接使用转义序列,例如

"\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
    
© www.soinside.com 2019 - 2024. All rights reserved.