简体   繁体   中英

How can I fix the problem with '\' character?

In the code I am converting every character to '(' if the appears only once in the whole string, or to ')' if it appears more than once. I pass almost all tests, except the test with input "$$\". It gives "missing terminating character" error. I see that problem is the '\' char. and if I add a second '\' it is good, but is there a quick way to fix it, or I should somehow add 1 to the size of the pointer and then add the second '\'?

PS The input is fixed. I cannot change it.

char text[] = "$$\";
char *res = malloc(strlen(text));
int counter = 0;
for(int i = 0; i < strlen(text); i++) {
    for(int j = 0; j < strlen(text); j++) {
        if( tolower(text[i]) == tolower(text[j]) )  {
            counter++;
        }
    }
    if(counter == 1) {
        res[i] = '(';
    } else {
        res[i] = ')';
    }
    printf("%c", res[i]);
    counter = 0;
}
return 0;

Since we are already proposing trigraphs, you can alternatively also use a magic number instead (x86 solution):

#include <stdio.h>
int main(void) 
{ 
  char* text = (char*)&(int) <%6038564%>;
  puts(text);
}

Output:

$$\

Or if you like the magic number 027022044 better, then go for that one instead.

(Not really a serious answer, but it's Friday, so...)

Nothing can escape from an escape character, even an escape character....

In C, all escape sequences consist of two or more characters

The first of which is the backslash, \ , called the Escape character.

The remaining characters determine the interpretation of the escape sequence.

Escape sequence of \\ equals 5C hex value in ascii which represents character of Backslash . Therefore in order to use backslash, you have to use it twice.

You can use trigraph sequence

char text[] = "$$??/"; // { dollar-sign, dollar-sign, backslash, zero }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM