将字符串转换为原始字符串 [英] Convert a string to raw string
问题描述
很容易声明一个原始字符串
It's easy so declare a raw string
String raw = @'\"Hello\"';
但是如何将现有字符串转换为原始字符串?
可以随文件读取或ajax调用一起来:我想将文件作为原始字符串读取,但是 readAsText
方法没有给我原始字符串。
我像这样的尝试:
But how can I convert a existing string to a raw string ?
This can come with file reading or ajax call : I want read the file as a raw string but the readAsText
method give me a no raw string.
I tryied thing like :
String notRaw = '\"Hello\"';
String raw = @raw;
但不进行编译。
我该怎么做?
But not compiling. How can I do this?
编辑:我需要按char读取字符串char。因此,我不想将\读为一个字符,而是读为两个字符\和
EDIT : My need is to read the string char by char. So I don't want to read \" as one char " but as two chars \ and "
推荐答案
想要在不解释转义字符的情况下读取文件,则需要 readAsBytes
,它将为您提供整数字符列表,然后您可以检测到反斜杠并引用为:
If you want to read a file without interpreting escape characters, then you need to readAsBytes
, which will give you a list of characters as integers. You can then detect a backslash and quote as:
final int backSlash = @'\'.charCodeAt(0);
final int quote = @'"'.charCodeAt(0);
然后将所需的子字符串传递给字符串构造函数:
You then pass the desired substrings to a string constructor:
String goodString = new String.fromCharCodes(byteList.getRange(start, end));
这篇关于将字符串转换为原始字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!