【问题标题】:Get substring of string using C使用C获取字符串的子字符串
【发布时间】:2014-12-13 17:55:58
【问题描述】:

假设我有一个这样的 const char* 字符串:

../products/product_code1233213/image.jpg

我想检索此路径字符串的倒数第二部分,即 jpg 文件的父文件夹名称,我该怎么做?

【问题讨论】:

标签: c char constants


【解决方案1】:

您可以使用strtok

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

int main()
{
   char str[] = "/products/product_code1233213/image.jpg";
   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);
}

输出:

products
product_code1233213
image.jpg

【讨论】:

  • 你不能在常量字符串上使用strtok()
  • @Ruslan 这被称为字符串文字,是的,修改它是非法的。但是 OP 对这个解决方案很满意。
  • 我确实做了一些调整以使其工作,通过 strcpy 到 char*
【解决方案2】:

此版本适用于const char *

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

int main()
{
    const char *s = "/products/product_code1233213/image.jpg";
    const char *p = s, *begin = s, *end = s;
    char *result;
    size_t len;

    while (p) {
        p = strchr(p, '/');
        if (p) {
            begin = end;
            end = ++p;
        }
    }
    if (begin != end) {
        len = end - begin - 1;
        result = malloc(len + 1);
        memcpy(result, begin, len);
        result[len] = '\0';
        printf("%s\n", result);
        free(result);
    }
    return 0;
}

【讨论】:

    【解决方案3】:

    仅使用 strchr() 且不回溯。快速且const-safe。

    #include <stddef.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define SEPARATOR '/'
    
    const char *path = "../products/product_code1233213/image.jpg";
    
    int main(void) {
        const char *beg, *end, *tmp;
    
        beg = path;
        if ((end = strchr(beg, SEPARATOR)) == NULL) {
            exit(1); /* no separators */
        }
        while ((tmp = strchr(end + 1, SEPARATOR)) != NULL) {
            beg = end + 1;
            end = tmp;
        }
        (void) printf("%.*s\n", (int) (end - beg), beg);
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-27
      • 2011-05-25
      • 2015-07-07
      • 2011-11-05
      • 2012-01-26
      • 2011-08-21
      • 2019-07-22
      相关资源
      最近更新 更多