You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C语言中删除字符串的最后部分?以路径截取为例

Hey there! Let's tackle this problem of stripping the last component from a path string. I get why strtok and strchr might have tripped you up—they work well for some string tasks but need a specific approach here. Here are a few solid methods to get what you want:

Method 1: Using strrchr (Simplest Approach)

strrchr finds the last occurrence of a character in a string—perfect for locating the final '/' in your path. Once you find it, you can just null-terminate the string right before that character.

#include <string.h>
#include <stdio.h>

int main() {
    char path[] = "folder1/folder2/folder3/folder4"; // Use a modifiable array, not a string literal!
    char *last_slash = strrchr(path, '/');
    
    if (last_slash != NULL) {
        *last_slash = '\0'; // Replace the last '/' with a null terminator
        printf("%s\n", path); // Output: folder1/folder2/folder3
    } else {
        // Handle cases where there are no slashes in the path
        printf("No slashes found in the path\n");
    }
    return 0;
}

Important note: Never pass a string literal (like const char *path = "...";) to this method—modifying string literals is undefined behavior in C. Always use a writable char array instead.

Method 2: Using dirname (POSIX Standard Function)

If you're working on a POSIX-compliant system (Linux/macOS), the dirname function from <libgen.h> does exactly what you need—it strips the last component of a path out of the box.

#include <libgen.h>
#include <stdio.h>
#include <string.h>

int main() {
    char path[] = "folder1/folder2/folder3/folder4";
    char *dir = dirname(path); // dirname may modify the input string, so use a copy if you need to keep the original
    
    printf("%s\n", dir); // Output: folder1/folder2/folder3
    return 0;
}

Heads up: dirname handles edge cases like paths ending with a '/' (it will strip the trailing empty component), so check its man page if you need to account for specific scenarios. If you want to preserve the original path, make a copy before passing it to dirname.

Method 3: Manual Traversal (No Library Dependencies)

If you want full control without relying on library functions, you can loop backwards from the end of the string to find the last '/'.

#include <stdio.h>
#include <string.h>

int main() {
    char path[] = "folder1/folder2/folder3/folder4";
    int len = strlen(path);
    
    // Move left from the end until we hit a '/'
    for (int i = len - 1; i >= 0; i--) {
        if (path[i] == '/') {
            path[i] = '\0';
            break;
        }
    }
    
    printf("%s\n", path); // Output: folder1/folder2/folder3
    return 0;
}

This method is great if you need to customize how you handle edge cases (like paths with multiple trailing slashes).

Pick the method that fits your environment and edge case needs—strrchr is probably the most straightforward for most scenarios!

内容的提问来源于stack exchange,提问作者Ozan Mudul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:02:32