c - 解析字符串并将其存储回字符数组时显示随机字节

标签 c string pointers

我正在尝试解析像 HTTP POST/abc/def/ghi/klm/mno 这样的字符串,我想在其中分离不同的组件,即协议(protocol)、HTTP 谓词和路径.

我正在使用 strtok 函数,然后使用 strlen 函数复制字符串。但是当我尝试打印字符串时,它给出了一些随机字节,如下所示。

enter image description here

我无法理解其中的原因。这就是我正在做的事情。

struct my_con {
    char protocol[100];
    char method[100];
    char uri[100];
};

char* header = "HTTP POST /abc/def/ghi/klm/mno";

void my_func(my_con **mc) {
   char* p = strtok(header," ");
   int c = 0;
   while(p != NULL) {

       if(count == 0) strncpy((**mc).protocol, p, strlen(p));
       elseif(count == 1) strncpy((**mc).method, p, strlen(p));
       elseif(count == 2) strncpy((**mc).uri, p, strlen(p));
       count++;
       p = strtok(NULL, " ");
   }
}

最佳答案

strspnstrcspn 可用于迭代文字字符串。

#include <stdio.h>
#include <string.h>

int main ( void) {
    char* header = "HTTP POST /abc/def/ghi/klm/mno";
    char temp[100];
    int offset = 0;
    int span = 0;

    while ( header[offset]) {
        span = strspn ( header + offset, " ");//count spaces
        offset += span;//advance offset past spaces
        span = strcspn ( header + offset, " ");//count non-space
        if (span && span < 99) {
            strncpy ( temp, header + offset, span);
            temp[span] = 0;//terminate
            printf ( "%s\n", temp);
        }
        offset += span;//advance offset past non-space
    }

    return 0;
}

关于c - 解析字符串并将其存储回字符数组时显示随机字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59800858/

相关文章:

c++ - 如何每 6 小时中断一次

c - 如何使用 ptrace 跟踪程序执行?

arrays - 将数值数组转换为字符串元胞数组

将 char 指针数组转换为 void 指针,然后再转换回来

c - 更新了 Leetcode 上的合并间隔问题 #56(特别是 C 语言)

c - 数组 : "error: reduction variable must be shared on entry to this OpenMP pragma" 中的 OpenMP SIMD 缩减

c - "Beginning C from Novice to Professional"中右移的用法误区

mysql - 确定最常用的词集php mysql

二进制值的 C++ 转义序列

c - C语言结构体的动态内存分配