文字列の一部を取得しようとしています。
次のコードがあります。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char mystring[]="The quick brown fox jumps over the lazy dog";
char word1[]="The";
char * posb,pose;
char * word2;
int b,e,n;
n=memcmp(mystring, word1, sizeof(word1)-1);
if (n==0) printf("the first word is found!\n");
posb=strchr(mystring,' '); // posb will be a pointer to the first character
b=posb-mystring+1;
printf("posb -> %d\n",posb);
printf("b -> %d\n",b);
pose=strchr(mystring+b+1,' '); // pose will be a pointer to the second character
printf("calc e\n");
e=pose-sizeof(mystring)+1;
printf("pose -> %s\n",pose);
printf("e -> %d\n",e);
word2 = (char*) malloc (sizeof(char)*(e-b));
memcpy(word2, posb, sizeof(word2));
printf("%s:%i:%i:%i\n",word2, b, e, e-b);
free (word2);
問題は、2 番目の単語を取得して word2 に格納することです。このために、使用strchr
してスペースを見つけようとします。しかし、2 回目に使用するときstrchr
は、2 番目のスペースを見つけるためにオフセットが必要です。私は次のことを試しました:
pose=strchr(mystring+b+1,' ');
pose=strchr(&mystring[b+1],' ');
変数b
とe
には、 の空白文字の位置が含まれている必要がありますmystring
。最終的にword2
含む必要があります。
別の解決策は、ループを使用して文字列を「ウォークスルー」することですが、それは関数をごまかすことになります。quick
strchr