gpt4 book ai didi

c - 如何用C更好的方式将字符串插入字符串?

转载 作者:行者123 更新时间:2023-11-30 18:44:36 25 4
gpt4 key购买 nike

我想做一些事情

char* a = "/data/cc/dd/ee/ff/1.jpg";

然后得到

char* b = "/data/cc/dd/ee/ff/json_1.json";

char *b = "/data/cc/dd/ee/1.txt";

这在 Python 中非常简单,但不幸的是我必须在 C 中做到这一点。我做了类似的事情:

Ubuntu C

char classpath[4096];
char *dirc, *basec, *bname, *dname;
find_replace(path, ".jpg", ".txt", classpath);
dirc = strdup(path);
basec = strdup(path);
dname = dirname(dirc);
bname = basename(basec);

我知道下一步应该是连接dname , 'json_'bname可能首先创建最终路径,如 char ressultpath[4096];然后使用strcat() ,但我想知道什么是使用更少内存和更快的更好方法,因为我真的不熟悉 C 。

最佳答案

您可以使用标准函数 strrchr() (它搜索字符串中字符的最后一个实例)来查找路径名中的最后一个 / 和文件名组件中的最后一个 . 。根据这些字符的位置(如果存在),您可以计算路径的目录和文件名部分的起始位置和长度。然后,您可以使用 snprintf() 函数以及这些起始位置和长度将目标中所需的文件名拼接在一起:

char classpath[4096];
const char *dir_end;
const char *name;
const char *suffix;
int dir_length;
int name_length;
int result_length;

/* Find the end of the directory component of the path, if it has one. */
dir_end = strrchr(path, '/');

if (dir_end)
{
/* The filename starts immediately after the final / */
name = dir_end + 1;
/* The length of the directory component up to and including the final / */
dir_length = dir_end - path + 1;
}
else
{
/* No directory component, so the filename begins at the start of the path */
name = path;
dir_length = 0;
}

/* Find the start of the file suffix, if it has one */
suffix = strrchr(name, '.');

if (suffix)
{
/* The length of the name not including the last . */
name_length = suffix - name;
}
else
{
/* No suffix at all, so the name is everything remaining */
name_length = strlen(name);
}

result_length = snprintf(classpath, sizeof classpath, "%.*sjson_%.*s.json", dir_length, path, name_length, name);

if (result_length >= sizeof classpath)
{
/* result was truncated */
}

关于c - 如何用C更好的方式将字符串插入字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57550837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com