C++ 在字符串中使用\作为文字而不是转义 boolstringmatch(constchar*expr,constchar*str){ //做一些比较*(expr+i)=='\\' //在本例中,它与反斜杠进行比较 //我是一个整数 } int main(){ 字符串a=“a\sb”; 字符串b=“a b”; cout
Xcode发出警告是因为它将“a\sb”中的C++ 在字符串中使用\作为文字而不是转义 boolstringmatch(constchar*expr,constchar*str){ //做一些比较*(expr+i)=='\\' //在本例中,它与反斜杠进行比较 //我是一个整数 } int main(){ 字符串a=“a\sb”; 字符串b=“a b”; cout,c++,xcode,string-literals,C++,Xcode,String Literals,Xcode发出警告是因为它将“a\sb”中的\s解释为转义序列,但\s不是有效的转义序列。它被替换为s,因此字符串变为“asb” 像“a\\sb”这样转义反斜杠是正确的解决方案。如果这对您不起作用,请发布更多详细信息 这里有一个例子 bool stringMatch(const char *expr, const char *str) { // do something to compare *(expr+i) == '\\' // In this case it is
\s
解释为转义序列,但\s
不是有效的转义序列。它被替换为s
,因此字符串变为“asb”
像“a\\sb”
这样转义反斜杠是正确的解决方案。如果这对您不起作用,请发布更多详细信息
这里有一个例子
bool stringMatch(const char *expr, const char *str) {
// do something to compare *(expr+i) == '\\'
// In this case it is comparing against a backslash
// i is some integer
}
int main() {
string a = "a\sb";
string b = "a b";
cout << stringMatch(a.c_str(), b.c_str()) << endl;
return 1;
}
#包括
#包括
int main(){
std::string a=“a\\sb”;
std::coutboolstringmatch(constchar*expr,constchar*str){
//做一些比较*(expr+i)=='\\'
//在本例中,它与反斜杠进行比较
//我是一个整数
}
int main(){
字符串a=“a\\sb”;
字符串b=“a b”;
cout.您的另一个选项是原始字符串文字,但除非您正在编写正则表达式或其他东西,否则这有点过分。a\\sb应该可以正常工作。请发布您看到的问题的详细信息。我已经尝试使用“a\\sb”,它以“a\\sb”的形式显示作为文字。请仔细检查,然后尝试我添加的示例程序。如果输出与预期的输出不同,请发布。您使用的是哪个IDE?Visual Studio
或DevC++
或其他什么?@YatingShengI无法重现警告。@YatingShengI您是否在Xcode@bames53中运行了代码?我运行了,但没有运行正常。这里不需要使用字符串文字连接;“a\x5Csb”也可以。另外,re:EDIT2,您在哪里看到了额外的反斜杠?它在调试器中吗?因为我相信Xcode调试器会显示转义的字符串。因此,包含单个反斜杠的正确字符串应该在调试器中显示为两个。无论您是将字符串初始化为“a\\sb”还是“a\x5csb”,这都是正确的。将其打印到控制台以查看实际内容。这就是问题所在,打印到控制台会去掉多余的反斜杠。re:Edit2-不,我在调试器中没有看到,这是基于我的测试用例得出的结论。@Bames53我想您的测试用例一定有问题。打印到控制台不会去掉横线中多余的反斜杠g、 如果反斜杠没有出现在打印到控制台的字符串中,那么它就不在字符串中。string a=“a\\sb”;assert(a[0]=“a”);assert(a[1]=“a\\”);assert(a[2]=“s”)
我可以向您保证,我的测试用例没有问题。您刚才键入的代码在字符级别上处理字符串
,这样,方法就不会看到额外的反斜杠,控制台显然会显示a\sb
@bames53是的,我在字符级别上查看字符串以确定只有y一个字符是斜杠。没有第二个斜杠字符。有什么测试表明字符串中有第二个斜杠字符?
#include <iostream>
#include <string>
int main() {
std::string a = "a\\sb";
std::cout << a.size() << ' ' << a << '\n';
}
void searchAndReplace(std::string& value, std::string const& search,std::string const& replace)
{
std::string::size_type next;
for(next = value.find(search); // Try and find the first match
next != std::string::npos; // next is npos if nothing was found
next = value.find(search,next) // search for the next match starting after
// the last match that was found.
)
{
// Inside the loop. So we found a match.
value.replace(next,search.length(),replace); // Do the replacement.
next += replace.length(); // Move to just after the replace
// This is the point were we start
// the next search from.
}
}
expr.replace(/*size_t*/ pos1, /*size_t*/ n1, /*const string&*/ str );
string a = R"raw(a\sb)raw";