Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

How to normalize the path(delete all repeated '/') in C

I am coding a program, that deletes all redundant / in the path of the file. In other words ///a/////b should become /a/b. I can delete all repeated /, but can't fully wrap my head about how to leave only one slash WITHOUT any standard function or indexation operation. Can someone fix my code, please?

#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
", path);
    normalize_path(path);
    printf("String after the function is used: %s
", path);
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can keep track if the previous character is slash, and add characters to the result if and only if at least either one of previous and current characters is not 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 != ''; in++) {
        if (!prev_is_slash || *in != '/') *(out++) = *in;
        prev_is_slash = *in == '/';
    }
    *out = '';
}

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...