如何从C中的char数组中获取字符串值
How to get the string value from a char array in C
我在 C
中有一个 char array
#define BUFSIZE 2048
unsigned char buf[BUFSIZE];
char request[10];
strcat(request "GET key01");
request[10] = '[=10=]';
buf = request;
请求来自具有 client-server socket
模拟的网络,但为了简单起见,我没有在此处包含它。
无论如何,我必须对 buf
字符串进行标记化,但还要保留一个未标记化的副本。我试过这个:
char* buf_for_token = buf;
printf("What is the buf before tokenization? %s\n", buf);
const char s[2] = " ";
char *token;
token = strtok(buf_for_token, s);
token = strtok(NULL, s);
printf("What is the buf after tokenization? %s\n", buf);
我的输出是:
What is the buf before tokenization? GET key01
What is the buf after tokenization? GET
我更喜欢:
What is the buf before tokenization? GET key01
What is the buf after tokenization? GET key01
如何从 char 数组中获取字符串的值并保存一个副本以便在不影响原始值的情况下进行操作?
您可以使用 C <string.h>
函数:
strcpy(const char *dest, const char *src);
将从 src 复制到 '\0' 字符,复制到 dest,并包括 '\0' 字符。
或
使用:
strcat(const char *dest, const char *src);
这将附加到已经存在的字符串的末尾,从 null 开始终止目标的 '\0',添加所有字符直到并包括 '\0'。
或
使用:
strncpy(const char *dest, const char *src, int size);
它将 n 个字符从 char *src 复制到 char *dest。
strtok
具有破坏性;当您通过用零字节覆盖定界符来对其进行标记化时,它将修改缓冲区的内容。如果您需要保留原始缓冲区内容,那么您将需要复制到另一个缓冲区并标记第二个缓冲区,或者您将需要使用 strtok
之外的内容(无论如何这通常是正确的答案)。
查看 strchr
或 strpbrk
等函数。您需要弄清楚如何提取单个标记并将其保存到另一个缓冲区,但这并不难。
我在 C
char array
#define BUFSIZE 2048
unsigned char buf[BUFSIZE];
char request[10];
strcat(request "GET key01");
request[10] = '[=10=]';
buf = request;
请求来自具有 client-server socket
模拟的网络,但为了简单起见,我没有在此处包含它。
无论如何,我必须对 buf
字符串进行标记化,但还要保留一个未标记化的副本。我试过这个:
char* buf_for_token = buf;
printf("What is the buf before tokenization? %s\n", buf);
const char s[2] = " ";
char *token;
token = strtok(buf_for_token, s);
token = strtok(NULL, s);
printf("What is the buf after tokenization? %s\n", buf);
我的输出是:
What is the buf before tokenization? GET key01
What is the buf after tokenization? GET
我更喜欢:
What is the buf before tokenization? GET key01
What is the buf after tokenization? GET key01
如何从 char 数组中获取字符串的值并保存一个副本以便在不影响原始值的情况下进行操作?
您可以使用 C <string.h>
函数:
strcpy(const char *dest, const char *src);
将从 src 复制到 '\0' 字符,复制到 dest,并包括 '\0' 字符。
或
使用:
strcat(const char *dest, const char *src);
这将附加到已经存在的字符串的末尾,从 null 开始终止目标的 '\0',添加所有字符直到并包括 '\0'。
或
使用:
strncpy(const char *dest, const char *src, int size);
它将 n 个字符从 char *src 复制到 char *dest。
strtok
具有破坏性;当您通过用零字节覆盖定界符来对其进行标记化时,它将修改缓冲区的内容。如果您需要保留原始缓冲区内容,那么您将需要复制到另一个缓冲区并标记第二个缓冲区,或者您将需要使用 strtok
之外的内容(无论如何这通常是正确的答案)。
查看 strchr
或 strpbrk
等函数。您需要弄清楚如何提取单个标记并将其保存到另一个缓冲区,但这并不难。