C中的字符串操作

时间:2013-05-23 12:45:24

标签: c substring

我有一个字符串,比如../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, "/");
    }

  }

3 个答案:

答案 0 :(得分:0)

试试这个:

char a[] = "../bin/a.cc";
char *tmp = strrstr(a, "/");
if (tmp != NULL) {
   tmp ++; 
   printf("%s", tmp); // you should get a.cc
}

答案 1 :(得分: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;    
}

答案 2 :(得分: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;
}