お世話になります。
今回、例えば
”/export/home/a/a.txt”
という文字列があった場合、”/export/home/a”までを取得したいのですが、
どうやったらいいのかさっぱりわかりません。。
”./b.txt”の場合は"."が取得したいです。
strtokで”/”を区切りにして・・・・とも思ったのですが、
どうにもスマートになりません。
どなたかいい方法を教えてください。。
文字列の検索?
Re:文字列の検索?
これは文字列内の最後の「/」より前の文字列を取得したいということでいいのですかね? であるならば、以下のプログラムでできます。 #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { const char* src = "/export/home/a/a.txt"; const char* p = strrchr(src, '/'); if (p != NULL) { const int len = p - src + 1; char* dst = (char*)malloc(len + 1); strncpy(dst, src, len); dst[len - 1] = '\0'; printf("%s\n", dst); free(dst); } return 0; }
Re:文字列の検索?
書いてたら解決しちゃいましたか。
文字列を読んでいき/の位置をendに記憶させ、最後の/を\0に変えています。
ポインタを使って書いていたんですがどうもうまくいかず配列にしてしまいました。
文字列を読んでいき/の位置をendに記憶させ、最後の/を\0に変えています。
ポインタを使って書いていたんですがどうもうまくいかず配列にしてしまいました。
#include <stdio.h> int main(void){ char str[/url] = "/export/home/a/a.txt"; int start = 0; int end = 0 ; while(str[start] != '\0'){ if(str[start] == '/') end = start; start++; } if(end != 0) str[end] = '\0'; printf("%s\n", str); return 0; }
Re:文字列の検索?
ちょっと冗長かな?(^_^;)
#include <stdio.h> #include <string.h> int main(void) { char str[/url] = "/export/home/a/a.txt"; size_t len = 0; for (len = strlen(str) - 1; len >= 0; --len) { if(*(str + len) == '/') { *(str + len) = '\0'; break; } } printf("%s\n", str); return 0; }
Re:文字列の検索?
すっごいあほなことやってたので、訂正 #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { const char* src = "/export/home/a/a.txt"; const char* p = strrchr(src, '/'); if (p != NULL) { const int len = p - src; char* dst = (char*)malloc(len + 1); strncpy(dst, src, len); dst[len] = '\0'; printf("%s\n", dst); free(dst); } return 0; } 元の文字列を壊していいなら↓ #include <stdio.h> #include <string.h> int main(void) { char s[/url] = "/export/home/a/a.txt"; char* p = strrchr(s, '/'); if (p != NULL) { *p = '\0'; printf("%s\n", s); } return 0; }