如何在 C 中规范化路径(删除所有重复的"/")

  • 本文关键字:删除 规范化 路径 c
  • 更新时间 :
  • 英文 :


我正在编写一个程序,该程序将删除文件路径中的所有冗余/。换句话说,CCD_ 2应当变成CCD_ 3。我可以删除所有重复的/,但无法完全理解如何在没有任何标准函数或索引操作的情况下只留下一个斜杠。有人能修一下我的代码吗?

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

您可以跟踪前一个字符是否为斜杠,并在前一个和当前字符中至少有一个不是斜杠的情况下向结果添加字符。

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

逻辑中断。特别是,索引i不应该减少,因为它对应于读取的字符。

更简单和正确的方法是使用两个索引,一个用于读取i,另一个用于写入k


#include <stdio.h>
//      ///a/////b
//      a/b/a
//      aa///b/a
void normalize_path(char *buf) {
int k = 0, counter = 0;
if (buf[0] == '') return;
for (int i = 0; buf[i]; i++) {
if (buf[i] == '/') {
++counter;
if (counter > 1) {
continue;
}
} else {
counter = 0;
}
buf[k] = buf[i];
k++;
}
buf[k] = '';
}

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

没有标准函数,也没有索引,使用指针:

char* normalize(char *s)
{
char *src = s;
char *dest = s;
while ((*dest = *src)) {
if (*dest == '/') {
// skip repeated slashes
while (*src=='/') {
src++;
}
dest++;
}
else {
src++;
dest++;
}
}
return s;
}

使用正则表达式(C:examples?中的正则表达式(,删除双斜杠的正则表达式位于从URL 中删除重复的正斜杠中

在如何在纯C中进行正则表达式字符串替换?是类似于PHPstr_replace的函数

最新更新