2013-05-23 2 views
0

문자열을 hava, 말하자면 ../bin/test.c, 그래서 어떻게 그 부분 문자열을 얻을 수 test?C에서 문자열 manuplation

나는 strtok api를 시도했지만 좋지 않은 것 같습니다.

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

    } 
+0

가능한 중복 [경로에서 파일 이름을 추출하는 방법 (http://stackoverflow.com/questions/7180293/추출 방법 - 파일 이름 - 경로에서) – user7116

+0

새 문자열에 값을 복사 하시겠습니까? 아니면 입력 문자열을 수정해도 괜찮습니까? strstr을 사용하여 두개의 문자열을 복사 할 수 없습니까? 아니면 두번째 문자열을 \ '로 대체하고 첫 번째 포인터를 사용합니까? – Rup

+0

간단한 검색 결과 표시 : http://stackoverflow.com/questions/6679204/how-to-get-substring-in-c – Stolas

답변

0

이 시도 :

char a[] = "../bin/a.cc"; 
char *tmp = strrstr(a, "/"); 
if (tmp != NULL) { 
    tmp ++; 
    printf("%s", tmp); // you should get a.cc 
} 
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;  
} 
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; 
}