usando \ en una cadena como literal en lugar de un escape

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.

preguntado el 24 de agosto de 12 a las 06:08

en.cppreference.com/w/cpp/language/escape. Your other option is a raw string literal, but unless you're writing a regex or something, it's a bit overkill. -

"a\\sb" should work fine. please post details on the problem you saw with it. -

2 Respuestas

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 - Retroceso
  • \f - Formfeed
  • \n - Nueva línea
  • \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.

Agregue código en su 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: Algunas personas piensan Editar 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: Si cambias el 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";

Tenga en cuenta que 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.

Respondido 17 ago 19, 10:08

There's no need to use string literal concatenation here; "a\x5Csb" would work. Also, re: EDIT2, where are you seeing the extra backslash? Is it in the debugger? Because I believe the Xcode debugger displays the strings escaped. So the correct string containing a single backslash should appear with two in the debugger. This will be true whether you initialize the string as "a\\sb" or "a\x5csb". Print it to the console to see the actual contents. - bames53

That's the point, printing to the console strips away the extra backslash. re: Edit2 -no I didn't see it in the debugger, it is a conclusion based on my test cases. @bames53 - Derpy Derp

I think something must be wrong with your test cases. Printing to the console does not strip extra backslashes from a string. If a backslash does not appear in a string printed to the console then it's not in the string. string a = "a\\sb"; assert(a[0] == 'a'); assert(a[1] == '\\'); assert(a[2] == 's'); - bames53

I can assure you, there's nothing wrong with my test cases. The code you just typed deals with the string en un character level, so this way, the methods won't see the extra backslash and the console would obviously show a\sb. @bames53 - Derpy Derp

Yes, I look at the string at a character level to determine that only one character is a slash. There is no second slash character. What tests do you have that show that there is a second slash character in the string? - bames53

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.

Aquí hay un ejemplo.

#include <iostream>
#include <string>

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

The output of this program looks like:

4 a\sb

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)".

Respondido 25 ago 12, 23:08

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

Double check that, and try the example program I've added. Post if the output is different from the expected output. - bames53

¿Qué IDE estás usando? Visual Studio or Bloodshed DevC++ or something else? @YatingSheng - Derpy Derp

I am not able to reproduce the warning. @YatingSheng - Derpy Derp

Did you run the code in Xcode @bames53? I did but it's running fine. - Derpy Derp

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.