0

I hava a string, say ../bin/test.c, so how can i get its substring test?

I tried strtok api, but it seems not good.

  char a[] = "../bin/a.cc";
  char *temp;
  if(strstr(a,"/") != NULL){
    temp = strtok(a, "/");
    while(temp !=NULL){
      temp = strtok(NULL, "/");
    }

  }
Foredoomed
  • 2,219
  • 2
  • 21
  • 39
  • possible duplicate of [How to extract filename from path](http://stackoverflow.com/questions/7180293/how-to-extract-filename-from-path) – user7116 May 23 '13 at 12:47
  • Do you want to copy the value to a new string or are you OK modifying the input string? Couldn't you just strstr the two /s and then copy the characters inbetween out, or replace the second one with a `'\0'` and use the first pointer? – Rup May 23 '13 at 12:48
  • A simple Search shows: http://stackoverflow.com/questions/6679204/how-to-get-substring-in-c – Stolas May 23 '13 at 12:49

3 Answers3

0

Try this:

char a[] = "../bin/a.cc";
char *tmp = strrstr(a, "/");
if (tmp != NULL) {
   tmp ++; 
   printf("%s", tmp); // you should get a.cc
}
TieDad
  • 9,143
  • 5
  • 32
  • 58
0
#include <stdio.h>
#include <string.h>

int main(void){
    char a[] = "../bin/a.cc";
    char name[16];
    char *ps, *pe;
    ps = strrchr(a, '/');
    pe = strrchr(a, '.');
    if(!ps) ps = a;
    else ps += 1;
    if(pe && ps < pe) *pe = '\0';
    strcpy(name, ps);

    printf("%s\n", name);
    return 0;    
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
0

The ugly one solution:

char a[] = "../bin/a.cc";
int len = strlen(a);
char buffer[100];
int i = 0;

/* reading symbols from the end to the slash */
while (a[len - i - 1] != '/') {
    buffer[i] = a[len - i - 1];
    i++;
}

/* reversing string */
for(int j = 0; j < i/2; j++){
    char tmp = buffer[i - j - 1];
    buffer[i - j - 1] = buffer[j];
    buffer[j] = tmp;
}
Alex
  • 9,891
  • 11
  • 53
  • 87