Reputation: 61
I am trying to parse the following string:
"USBSTOR\DISK&VEN_JETFLASH&PROD_TRANSCEND_8GB&REV_1100\00H8096XQ9UW1BQ5&0:JetFlash Transcend 8GB USB Device"
based on '\'
(character)
Prob 1: but this character is considered as escape character
Prob 2: \0
in the mid of the string is considered as the end of the string.
I tried so many ways.
(i) I tried to replace '\'
with another character like '$'
and tried to parse with sscanf()
but it did not work.
Can you people suggest something?
#include <string.h>
#include <stdio.h>
int main()
{
char str[80] = "This is \www.tutorialspoint.com \website";
const char s[2] = "\\";
char *token;
/* get the first token */
token = strtok(str, s);
/* walk through other tokens */
while( token != NULL )
{
printf( " %s\n", token );
token = strtok(NULL, s);
}
return(0);
}
Upvotes: 0
Views: 1321
Reputation: 6116
Remember Escape Sequences (\\
, \n
, \0
, etc.)are a single character.
To have \
character in a string which is initialized in the code itself, it is mandatory to use \\
in the initialization string.
If you are providing input at runtime, then you should use \
(Single BackSlash) for input, Providing input this way will not consider \0
as ASCII-0 character, instead it will be treated as \
followed by 0
(two characters).
In your case, you want to parse "USBSTOR\D...", you can do it in either by storing it in a const
string (Remember \\
in this case) or by providing it as input form console or a disk file (Here you should use single \
).
In any of the above ways, when you read the string, you will get the correct character expected, example, for first case \\
will resolve to \
when you read it or print it.
Upvotes: 1
Reputation: 3106
Make this modification
char str[80] = "This is \\www.tutorialspoint.com \\website";
With that, your output is:
This is
www.tutorialspoint.com
website
Remember: Any string literal that you use in code requires the escape sequence for backslash.
Upvotes: 1