[英]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.