0

我有一个字符串,比如说../bin/test.c,我怎样才能得到它的子字符串test

我试过strtokapi,但似乎不太好。

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

  }
4

3 回答 3

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;    
}
于 2013-05-23T12:56:04.083 回答
0

尝试这个:

char a[] = "../bin/a.cc";
char *tmp = strrstr(a, "/");
if (tmp != NULL) {
   tmp ++; 
   printf("%s", tmp); // you should get a.cc
}
于 2013-05-23T12:50:58.143 回答
0

丑陋的一种解决方案:

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;
}
于 2013-05-23T13:28:27.847 回答