【问题标题】:Limit string from another string从另一个字符串限制字符串
【发布时间】:2021-07-18 15:40:32
【问题描述】:

我有

char filemem[14], *file, *path;
file = strcpy(filemem,"/path/to/file");
path = file - 4;

我想要char *path = file - 4,这样char *path 只能读取/path/to/。是否可以显示指针的一部分而不必将字符串的副本创建到另一个内存中

【问题讨论】:

  • char *file = /path/to/file; 不是有效的 C 代码。
  • 如果可以修改字符串,可以在/path/to/之后的位置分配一个空字节
  • 不,这是不可能的,如果您希望两个字符串都有效或字符串不可修改(例如字符串文字)。
  • 首先考虑单独保留文件夹路径。
  • 是的,它依赖于知道文件名的最大长度。而strcpy 返回目标指针,所以path = file - 4;(即filemem - 4)没有用处。

标签: c string pointers


【解决方案1】:

在 C 中,字符串总是以 NUL 字节 ('\0') 结束。

char *path = file - 4 将指向file 指针前面四个字节的地址。这并不意味着“将字符串截断四个字节”。

为了截断一个字符串,你必须在你想要的最后一个字符之后放置一个 NUL 字节。如果您的字符串是只读的,您必须有额外的内存来复制所需的字符。没有办法让 C 字符串的切片在 NUL 终止字节之前结束,并且对于期望 NUL 终止字符串的函数仍然有效。

一些例子:

修改现有字符串:

int main(void) {
    char file[] = "/path/to/file";
    strrchr(file, '/')[1] = '\0';

    puts(file);
}

从只读内存复制子串:

char *repath(const char *path) {
    size_t len = strrchr(path, '/') - path + 1;
    return strncpy(calloc(len + 1, 1), path, len);
}

int main(void) {
    const char *file = "/path/to/file";
    char *fileless = repath(file);

    puts(fileless);
    free(fileless);
}

(为简洁起见,两个示例中都省略了错误处理。strrchrcalloc 可以返回 NULL。)

【讨论】:

    【解决方案2】:

    如果“显示”是指打印,则可以在使用printf 格式化字符串以截断它时使用%.*s 作为可变精度说明符:

        const char * path = "/path/to/file";
        int filename_offset = strrchr(path,'/') - path +1;
        
        printf("path     : %.*s\n", filename_offset, path);
        printf("filename : %s\n", path + filename_offset);
    

    输出:

    path     : /path/to/
    filename : file
    

    【讨论】:

      猜你喜欢
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      相关资源
      最近更新 更多