反斜杠和引号不计入字符串长度?

Backslashes and quotes not getting counted to string length?

本文关键字:字符串      更新时间:2023-10-16

我得到了用字符串编写的JSON。Notepad++ 中的长度显示 210 个字符,但在 C+++ 中只有 182 个字符。

如何在C++中获得 210 个字符?

带有转义引号的示例 JSON:

{"_id":"5de2dff0d6c9e312d659bc42","index":"0","guid":"eba0e936-0b18-48ec-88ca-00312ede4a7d","isActive":"false","balance":"$1,636.50","picture":"http://placehold.it/32x32","age":"36"}

和我的代码:

#include <iostream>
using namespace std;
int main()
{
//210 characters
string str = "{"_id":"5de2dff0d6c9e312d659bc42","index":"0","guid":"eba0e936-0b18-48ec-88ca-00312ede4a7d","isActive":"false","balance":"$1,636.50","picture":"http://placehold.it/32x32","age":"36"}";
cout << "String Length = " << str.length(); // return 182
return 0;
}

每个"最终都不是两个不同的字符,而只是一个"字符,这就是为什么字符计数似乎不正常的原因。这样做的原因是字符串文本中的双引号需要转义。

您可以使用原始字符串文字来保存此字符串,因为每个都将被视为其中的文字反斜杠字符,因此每个"都只表示反斜杠 + 双引号:

#include <iostream>
using namespace std;
int main()
{
string str = R"({"_id":"5de2dff0d6c9e312d659bc42","index":"0","guid":"eba0e936-0b18-48ec-88ca-00312ede4a7d","isActive":"false","balance":"$1,636.50","picture":"http://placehold.it/32x32","age":"36"})";
cout << "String Length = " << str.length();
return 0;
}

输出:

String Length = 210