简体   繁体   中英

How to remove the last string token from a path

I have a string like "\\\\PC1\\Users\\Administrator\\Last\\" . I wanted to remove the last part of the string, I mean Last. I used the following code but it doesn't work.

 char str1[] = "\\\\PC1\\C$\\Users\\Administrator\\Last\\";

 char* temp;
 temp = strchr(str1, '\\');   //Get the pointer to char token
 *temp = '\0';
 printf("%s\n", str1);

You are better served using strrchr() to obtain a pointer to the last occurrence of '\\' in str1 rather than obtaining a pointer to the first with strchr() . All that is needed is to loop while getting a pointer to the last '\\' and check if the next character is the nul-terminating character, overwriting '\\' each time with the nul-terminating character. On exit, check you exited as a result of finding '\\' where the following character was not the nul-character and nul-terminate once more for your final solution:

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

int main (void) {

    char str1[] = "\\\\PC1\\C$\\Users\\Administrator\\Last\\";
    char *temp = strrchr (str1, '\\');      /* find last \\ */

    while (temp && !temp[1]) {              /* valid ptr & next is nul-character */
        *temp = 0;                          /* nul-terminate at current */
        temp = strrchr (str1, '\\');        /* get next last \\ */
    }
    if (temp)                               /* if not NULL */
        *temp = 0;                          /* nul-terminate at current */

    printf ("%s\n", str1);                  /* output results */
}

If you want to preserve the last path separator following "...Administrator\" , then make the final termination at temp[1] , eg

    if (temp)                               /* if not NULL */
        temp[1] = 0;                        /* nul-terminate at next */

This will work regardless of whether the string ends with '\\' . For example, it will work equally well with:

char str1[] = "\\\\PC1\\C$\\Users\\Administrator\\Last";

Example Use/Output

Removing the path separator after "...Administrator" by making the final termination at *temp :

$ ./bin/trimlast
\\PC1\C$\Users\Administrator

or if preserving the final separator terminating at temp[1] :

$ ./bin/trimlast
\\PC1\C$\Users\Administrator\

( note: windows accepts '/' instead of '\\' in virtually all path circumstances in C -- which makes things a bit easier on the eyes)

Look things over and let me know if you have questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM