[英]Matching of strings with special characters
我需要生成一个可以匹配另一个包含特殊字符的字符串。 我写了我认为是一个简单的方法,但到目前为止还没有给我一个成功的匹配。
我知道 C++ 中的特殊字符以“\\”开头。 例如,单引号将写为“\\'”。
string json_string(const string& incoming_str)
{
string str = "\\\"" + incoming_str + "\\\"";
return str;
}
这是我必须比较的字符串:
bool comp = json_string("hello world") == "\"hello world\"";
我可以在 cout 流中看到,实际上我正在根据需要生成字符串,但比较仍然给出false
值。
我错过了什么? 任何帮助,将不胜感激。
一种方法是过滤一个字符串并比较这个过滤后的字符串。 例如:
#include <iostream>
#include <algorithm>
using namespace std;
std::string filterBy(std::string unfiltered, std::string specialChars)
{
std::string filtered;
std::copy_if(unfiltered.begin(), unfiltered.end(),
std::back_inserter(filtered), [&specialChars](char c){return specialChars.find(c) == -1;});
return filtered;
}
int main() {
std::string specialChars = "\"";
std::string string1 = "test";
std::string string2 = "\"test\"";
std::cout << (string1 == filterBy(string2, specialChars) ? "match" : "no match");
return 0;
}
输出是match
。 如果向specialChars
添加任意数量的字符,此代码也有效。
如果两个字符串都包含特殊字符,还可以通过filterBy
函数放入string1
。 然后,类似于:
"\"hello \" world \"" == "\"hello world "
也会匹配。
如果比较对性能至关重要,您可能还需要使用两个迭代器进行比较,得到 log(N+M) 的比较复杂度,其中 N 和 M 分别是两个字符串的大小。
bool comp = json_string("hello world") == "\"hello world\"";
这肯定会产生错误。 您正在通过json_string("hello world")
创建字符串\\"hello world\\"
,但将其与"hello world"
进行比较
问题在这里:
string str = "\\\"" + incoming_str + "\\\"";
在 str 的第一个字符串文字中,您假设被视为转义字符的第一个字符反斜杠实际上并未被视为转义字符,而只是字符串文字中的反斜杠。 你在最后一个字符串文字中做同样的事情。
这样做:
string str = "\"" + incoming_str + "\"";
在 C++ 中,字符串文字由引号分隔。
那么问题来了:如何定义一个本身包含引号的字符串文字? 在 Python 中(为了比较),这很容易(但这种方法还有其他缺点,这里不感兴趣): 'a string with " (quote)'
。
C++ 没有这种替代字符串表示1 ,相反,您只能使用转义序列(也可以在 Python 中使用 - 只是为了完整性......):在字符串(或字符)文字中(但没有其他地方! ),序列\\"
将被结果字符串中的单引号替换。
所以定义为字符数组的"\\"hello world\\""
将是:
{ '"', 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '"', 0 };
请注意,现在不需要转义字符...
但是,在json_string
函数中,您附加了额外的反斜杠:
"\\\""
{ '\', '"', 0 }
//^^^
请注意,我写的'\\'
只是为了说明! 你如何定义单引号? 又要逃了! '\\''
- 但是现在您也需要转义转义字符,因此实际上需要在此处将单个反斜杠写为'\\\\'
(相比之下,您不必转义字符串中的单引号文字: "i am 'singly quoted'"
——就像你不必在字符文字中转义双引号一样)。
由于 JSON 也对字符串使用双引号,因此您很可能希望更改您的函数:
return "\"" + incoming_str + "\"";
甚至更简单:
return '"' + incoming_str + '"';
现在
json_string("hello world") == "\"hello world\""
会产生真正的...
1旁注(从同时删除的答案中窃取):从 C++11 开始,也有原始字符串文字。 使用这些,你也不必逃避。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.