ページ 11

文字列の検索?

Posted: 2009年4月10日(金) 13:04
by piyo
お世話になります。
今回、例えば
”/export/home/a/a.txt”
という文字列があった場合、”/export/home/a”までを取得したいのですが、
どうやったらいいのかさっぱりわかりません。。

”./b.txt”の場合は"."が取得したいです。

strtokで”/”を区切りにして・・・・とも思ったのですが、
どうにもスマートになりません。
どなたかいい方法を教えてください。。

Re:文字列の検索?

Posted: 2009年4月10日(金) 13:25
by GPGA
これは文字列内の最後の「/」より前の文字列を取得したいということでいいのですかね?
であるならば、以下のプログラムでできます。

#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:文字列の検索?

Posted: 2009年4月10日(金) 14:21
by nayo
文字列をいったんすべて読んでしまった後、文字列の後ろから「/」を探して、
見つけたら\0に置き換えるとかどうでしょうか

Re:文字列の検索?

Posted: 2009年4月10日(金) 15:20
by piyo
お返事ありがとうございます!!

思っていたようにできました。

Re:文字列の検索?

Posted: 2009年4月10日(金) 15:28
by hss12
書いてたら解決しちゃいましたか。
文字列を読んでいき/の位置を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:文字列の検索?

Posted: 2009年4月10日(金) 16:27
by バグ
ちょっと冗長かな?(^_^;)

#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:文字列の検索?

Posted: 2009年4月10日(金) 16:34
by Blue
素直にstrrchr使えばいいのでは?

Re:文字列の検索?

Posted: 2009年4月10日(金) 17:14
by GPGA
すっごいあほなことやってたので、訂正

#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;
}