我有一个字符串,比如说../bin/test.c
,我怎样才能得到它的子字符串test
?
我试过strtok
api,但似乎不太好。
char a[] = "../bin/a.cc";
char *temp;
if(strstr(a,"/") != NULL){
temp = strtok(a, "/");
while(temp !=NULL){
temp = strtok(NULL, "/");
}
}
#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;
}
尝试这个:
char a[] = "../bin/a.cc";
char *tmp = strrstr(a, "/");
if (tmp != NULL) {
tmp ++;
printf("%s", tmp); // you should get a.cc
}
丑陋的一种解决方案:
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;
}