首页 > 解决方案 > 如何在C中规范化路径(删除所有重复的'/')

问题描述

我正在编写一个程序,该程序会删除/文件路径中的所有冗余。换句话说///a/////b应该成为/a/b。我可以删除所有重复/的,但不能完全理解如何在没有任何标准功能或索引操作的情况下只留下一个斜线。有人可以修复我的代码吗?

#include <stdio.h>

//      ///a/////b
//      a/b/a
//      aa///b/a
void normalize_path(char *buf) {
    int k = 0, counter = 0;
    for (int i = 0; buf[i]; i++) {
        buf[i] = buf[i + k];

        if (buf[i] == '/') {
            ++counter;
            if (counter > 1) {
                --i;
                ++k;
            } else {
                ++k;
            }
        } else {
            counter = 0;
        }
    }
}



int main() {
    char path[100];
    scanf("%s", path);
    printf("String before the function: %s\n", path);
    normalize_path(path);
    printf("String after the function is used: %s\n", path);
    return 0;
}

标签: c

解决方案


如果前一个字符是斜线,您可以跟踪,当且仅当前一个字符和当前字符中的至少一个不是 shash 时,才将字符添加到结果中。

#include <stdio.h>

//      ///a/////b
//      a/b/a
//      aa///b/a
void normalize_path(char *buf) {
    char *in = buf, *out = buf;
    int prev_is_slash = 0;
    for (; *in != '\0'; in++) {
        if (!prev_is_slash || *in != '/') *(out++) = *in;
        prev_is_slash = *in == '/';
    }
    *out = '\0';
}

int main() {
    char path[100];
    scanf("%s", path);
    printf("String before the function: %s\n", path);
    normalize_path(path);
    printf("String after the function is used: %s\n", path);
    return 0;
}

推荐阅读