0

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

2 回答 2

1

请记住转义序列(\\\n\0等)是单个字符。

\在代码本身中初始化的字符串中包含字符,必须\\在初始化字符串中使用。

如果您在运行时提供输入,那么您应该使用\(Single BackSlash) 进行输入,以这种方式提供输入不会\0视为 ASCII-0 字符,而是会被视为\后跟0(两个字符)。

在您的情况下,您想要解析"USBSTOR\D...",您可以通过将其存储在const字符串中(\\在这种情况下请记住)或将其作为输入表单控制台或磁盘文件提供(在这里你应该使用单\)。

在上述任何一种方式中,当您读取字符串时,您将获得预期的正确字符,例如,当您读取或打印它时,第一种情况\\将解析为。\

于 2013-10-15T06:05:37.620 回答
1

进行此修改 char str[80] = "This is \\www.tutorialspoint.com \\website";

有了这个,你的输出是:

This is 
www.tutorialspoint.com 
website

请记住:您在代码中使用的任何字符串文字都需要反斜杠的转义序列。

于 2013-10-15T05:56:25.067 回答