How to get the last part of a string in C

I have a line in C that contains a file path, for example, home / usr / wow / muchprogram.

I was wondering in C how I can get the line after the last "/". So, I could store it as a variable. This variable will be equal to "muchprogram" to be clear.

I also wonder how I could get everything to the final "/". Thanks in advance.

+3
source share
5 answers

Start scanning the line from the end. As soon as you stop /. Pay attention to indexand copy from index+1to last_indexinto a new array.

/. index. start_index index-1 .

+1

, '/'. . , '/' ( '/' '\0'), '/'.

0

- , C. , , . GCC 4.7.3.

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

int main() {
  char* s = "home/usr/wow/muchprogram";
  int n = strlen(s);
  char* suffix = s + n;

  printf("%s\n%s\n", s, suffix);

  while (0 < n && s[--n] != '/');
  if (s[n] == '/') {
    suffix = s + n + 1;
    s[n] = '\0';
  }

  printf("%s\n%s\n", s, suffix);
  return 0;
}
0

strrchr(3) C89 .

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

static void find_destructive(char *s) {
    char *p_sl = strrchr(s, '/');
    if (p_sl) {
        *p_sl = '\0';
        printf("[%s] [%s]\n", s, p_sl + 1);
    } else {
        printf("Cannot find any slashes.\n");
    }
}

static void find_transparent(const char *s) {
    const char *p_sl = strrchr(s, '/');
    if (p_sl) {
        char *first = (char *)malloc(p_sl - s + 1);
        if ( ! first) {
            perror("malloc for a temp buffer: ");
            return;
        }
        memcpy(first, s, p_sl - s);
        first[p_sl - s] = '\0';
        printf("[%s] [%s]\n", first, p_sl + 1);
        free(first);
    } else {
        printf("Cannot find any slashes.\n");
    }
}

int main() {
    char s[] = "home/usr/wow/muchprogram";

    find_transparent(s);
    find_destructive(s);

    return 0;
}
0

# .

Var tokens = Str.Split('/');
Var lastItem = tokens[tokens.Length-1];
Var everythingBeforeLastItem = string.Empty;
Enumerate.Range(0,tokens.Length-3).ToList().
ForEach(i => everythingBeforeLastItem = everythingBeforeLastItem+tokens[i]+"\");
EverythingBeforeLastItem += tokens[tokens.Length-2];

StringBuilder , , .

0

All Articles