c - 如何在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;
}
解决方案
如果前一个字符是斜线,您可以跟踪,当且仅当前一个字符和当前字符中的至少一个不是 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;
}
推荐阅读
- php - SQL 不接受包含带有冒号 (":") 的值的 INSERT INTO
- c# - 如何使用服务类使我的 web-api 与我的控制器一起工作?
- c++ - 复制构造函数并从方法中获取数据
- java - 使用 Fisica/Box2D 在处理中滚动背景
- lua - debug.getinfo(1, "n").name 引起的奇怪行为
- javascript - 如何使用 CryptoJS AES 解密消息?我有一个工作节点加密示例
- swift - 如何在 Swift UI 上的 TextField 和 Text 组件中放置多行(断行)?
- batch-file - 批处理文件循环 - 运行所有满足 findstr 条件的文件
- c# - 如何添加多个消费者从 kafka 流中消费?
- python - 没有找到 numpy 的匹配分布(来自 torch==1.10)