ページ 1 / 1
文字列から全ての単語を取得
Posted: 2008年2月11日(月) 06:26
by ワグナス
char型の配列(の配列)に入っている文字列から全ての単語を取り出す方法について考えております。
#include <stdio.h>
int main(void){
char str[4][64] = {
"This is a pen",
"I am student",
"What is it",
"May I help you",
};
char ary[30][16];
return 0;
}
このように str に文字列が入っているとき、C言語で単語を ary に格納することはできるのでしょうか?(配列の大きさは適当です)
string風に書くと、
ary[0] = "This";
ary[1] = "is";
ary[2] = "a";
ary[3] = "pen";
ary[4] = "I";
ary[5] = "am";
...
のようになることが理想なのですが、スマートな方法はあるのでしょうか?
sscanfでできないかと思ったのですが、istrstreamのように読み込み位置(シーク位置)を記憶できないのでよい方法が思いつきませんでした。
これについて何かよい方法があればご教示頂きたく思います。
宜しくお願いします。
Re:文字列から全ての単語を取得
Posted: 2008年2月11日(月) 06:40
by tk-xleader
strtok関数を使うとか。ぐらいしか思いつきません。
Re:文字列から全ての単語を取得
Posted: 2008年2月11日(月) 07:54
by
#include <stdio.h>
#include <string.h>
int main(void){
char str[4][64] = {
"This is a pen",
"I am student",
"What is it",
"May I help you",
};
char ary[30][16];
char *token, *dlm = " ";
int i, j;
for (i = j = 0; i < sizeof(str) / sizeof(str[0]); i++) {
token = strtok(str, dlm);
while (token) {
strcpy(ary[j++], token);
token = strtok(NULL, dlm);
}
}
for (i = 0; i < j; i++)
printf("%s\n", ary);
return 0;
}
Re:文字列から全ての単語を取得
Posted: 2008年2月11日(月) 09:55
by フリオ
スマートかどうか解りませんが、こんな方法はどうでしょう。
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[4][64] = {
"This is a pen",
"I am student",
"What is it",
"May I help you",
};
char ary[30][16];
int i, j, k;
for(j = i = 0; i < 4; i ++){
k = 0;
ary[j][0] = '\0';
do{
sscanf(&str[k], "%s", ary[j]);
k += strlen(ary[j]);
j ++;
}while(str[k ++]);
}
for(i = 0; i < j; i ++) puts(ary);
return 0;
}
Re:文字列から全ての単語を取得
Posted: 2008年2月11日(月) 11:54
by Justy
> istrstreamのように読み込み位置(シーク位置)を記憶できないのでよい方法が思いつきませんでした。
読み込み位置というかどこまで読んだかは %nで取得できますよ。
[color=#d0d0ff" face="monospace] int n, count = 0;
for(n=0; n<sizeof(str)/sizeof(str[0]); ++n){
const char *p = &str[n][0];
do{
int pos;
if(sscanf(p, " %s %n", ary[count++], &pos) == 1)
p += pos;
}while(*p != '\0');
}[/color]
Re:文字列から全ての単語を取得
Posted: 2008年2月11日(月) 17:17
by たかぎ
strpbrk とか strcspn を使うのも一つの手です。
その場合、おそらく strspn も組み合わせる必要があるでしょう。
Re:文字列から全ての単語を取得
Posted: 2008年2月12日(火) 03:08
by ワグナス
ご回答いただきありがとうございます。
みなさまのコードを例示していただき参考になりました。
これに関しての有用な関数やアプローチを複数拝見でき、手法をより明確に認識することができました。
ありがとうございました。