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

时间:2015-09-25 08:18:34

标签: c

我正在使用以下代码向后遍历一个树,而我现在得到的是最后的分隔符,例如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;
}

1 个答案:

答案 0 :(得分:5)

假设您获得的每个输出都具有该正斜杠,您只需将其从最终输出中删除即可。在下面的代码片段中,我有条件地检查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"
相关问题