gpt4 book ai didi

c - 删除字符串末尾的路径分隔符

转载 作者:太空狗 更新时间:2023-10-29 15:28:47 28 4
gpt4 key购买 nike

我正在使用以下代码向后遍历树,我现在得到的是末尾的分隔符,例如 child/grandchild/<-- 我想删除该分隔符。我不知道要在算法中修改什么才能这样做。

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

struct node { struct node *parent; char *name; };

char *buildPath(node* node, bool use_register_name)
{
struct node *temp = node;
int length =0;
do
{
length+=strlen(temp->name)+1; // for a slash;
temp = temp->parent;
} while(temp !=NULL);
char * buffer =malloc(length+1);
buffer[0] = '\0';
do
{
if(!use_register_name)
{
use_register_name=true;
node = node->parent;
continue;
}
char *name = strdup(node->name);
strcat(buffer,"/");
strrev(name);
strcat(buffer,name);

node = node->parent;
free(name);
} while (node != NULL &&strcmp(node->name,"root")<0);
strrev(buffer);
return buffer;
}

int main(void)
{
struct node node1 = { NULL, "root" };
struct node node2 = { &node1, "child" };
struct node node3 = { &node2, "grandchild" };
char * result = buildPath(&node3, false);
printf(result);
return EXIT_SUCCESS;
}

最佳答案

假设您获得的每个输出都有尾部正斜杠,您可以简单地将其从最终输出中删除。在下面的代码片段中,我有条件地检查 result 是否至少有一个字符,并且最后一个字符是正斜杠。如果满足这些条件,我将删除正斜杠。

char * result = buildPath(&node3, false);

if (result && *result) { // make sure result has at least
if (result[strlen(result) - 1] == '/') // one character
result[strlen(result) - 1] = 0;
}

更新:

这是您的问题的解决方案,它修改了算法本身。尝试将您的代码修改为以下内容:

int firstCall = 1; // flag to keep track of whether this is first call (leaf node)

do {
if(!use_register_name)
{
use_register_name=true;
node = node->parent;
continue;
}
char *name = strdup(node->name);
if (firstCall) {
firstCall = 0;
}
else {
// ONLY add this slash to a non-terminal node
strcat(buffer,"/");
}
strrev(name);
strcat(buffer,name);

node = node->parent;
free(name);
} while (node != NULL &&strcmp(node->name,"root")<0);

这是您的算法当前如何为您的 OP 中的输入构建路径:

buffer = "/dlihcdnarg"        // note carefully this leading (really trailing) slash
buffer = "/dlihcdnarg/dlihc"

然后您的代码在某个时候反转缓冲区以获得此:

"child/grandchild/"

在这种情况下,通过添加对叶节点的检查,而不是添加前导(实际上是尾随)斜杠,您将获得以下输出:

"child/grandchild"

关于c - 删除字符串末尾的路径分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32777785/

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