using \ in a string as literal instead of an escape

大兔子大兔子 提交于 2020-01-08 13:24:17

问题


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

So the problem right now is: Xcode is not reading in the '\', when I was debugging in stringMatch function, expr appears only to be 'asb' instead of the literal a\sb'.

And Xcode is spitting out an warning at the line: string a = "a\sb" : Unknown escape sequence

Edit: I have already tried using "a\\sb", it reads in as "a\\sb" as literal.


回答1:


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

C and C++ deal with backslashes as escape sequences by default. You got to tell C to not use your backslash as an escape sequence by adding an extra backslash to your string.

These are the common escape sequences:

  • \a - Bell(beep)
  • \b - Backspace
  • \f - Formfeed
  • \n - New line
  • \r - Carriage Return
  • \t - Horizontal Tab
  • \\ - Backslash
  • \' - Single Quotation Mark
  • \" - Double Quatation Mark
  • \ooo - Octal Representation
  • \xdd - Hexadecimal Representaion

EDIT: Xcode is behaving abnormally on your machine. So I can suggest you this.

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" "\x5C" "sb";
    string b = "a b";
    cout << stringMatch(a.c_str(), b.c_str()) << endl;
    return 1;
}

Don't worry about the spaces in the string a declaration, Xcode concatenates strings separated with a space.

EDIT 2: Indeed Xcode is reading your "a\\b" literally, that's how it deals with escaped backslashes. When you'll output string a = "a\\sb" to console, you'll see, a\sb. But when you'll pass string a between methods as argument or as a private member then it will take the extra backslash literally. You have to design your code considering this fact so that it ignores the extra backslash. It's upto you how you handle the string.

EDIT 3: Edit 1 is your optimal answer here, but here's another one.

Add code in your stringMatch() method to replace double backslashes with single backslash.

You just need to add this extra line at the very start of the function:

expr=[expr stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"];

This should solve the double backslash problem.

EDIT 4: Some people think Edit 3 is ObjectiveC and thus is not optimal, so another option in ObjectiveC++.

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. 
    }
}


EDIT 5: If you change the const char * in stringMatch() to 'string` it will be less complex for you.

expr.replace(/*size_t*/ pos1, /*size_t*/ n1, /*const string&*/ str );

EDIT 6: From C++11 on, there exists something like raw string literals. This means you don't have to escape, instead, you can write the following:

string a = R"raw(a\sb)raw";

Note that the raw in the string can be replaced by any delimiter of your choosing. This for the case you want to use a sub string like )raw in the actual string. Using these raw string literals mainly make sense when you have to escape characters a lot, like in combination with std::regex.

P.S. You have all the answers now, so it's upto you which one you implement that gives you the best results.




回答2:


Xcode is spitting out that warning because it is interpreting \s in "a\sb" as an escape sequence, but \s is not a valid escape sequence. It gets replaced with just s so the string becomes "asb".

Escaping the backslash like "a\\sb" is the correct solution. If this somehow didn't work for you please post more details on that.

Here's an example.

#include <iostream>
#include <string>

int main() {
    std::string a = "a\\sb";
    std::cout << a.size() << ' ' << a << '\n';
}

The output of this program looks like:

If you get different output please post it. Also please post exactly what problem you observed when you tried "a\\sb" earlier.


Regexs can be a pain in C++ because backslashes have to be escaped this way. C++11 has raw strings that don't allow any kind of escaping so that escaping the backslash is unnecessary: R"(a\sb)".



来源:https://stackoverflow.com/questions/12103445/using-in-a-string-as-literal-instead-of-an-escape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!