将字符串转换为原始字符串

将字符串转换为原始字符串

问题描述:

很容易声明一个原始字符串

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));