2017-02-09 15 views
0

文字列内の単語をC言語で選択するにはどうすればよいですか?C言語のテキスト行の単語を選択する方法

例の文字列「私の母はよく調理します....」その文字列の「料理」だけをどのように編集できますか?問題は試験のためです。どのように長さを見つけることができますか?たとえば、テキストの2番目の単語を編集するにはどうすればよいですか?

#include <stdio.h> 

int length(char* s) // Lenght 
{ 
    int d = -1; 
    while (s[++d]); 
    return d; 
} 

int main() //main function 
{ 
    char str[101], c; 
    int i = 0; 

    printf("Entry text:\n"); 
    scanf("%s", str); //Input text line 
    printf("First word lenght('%s') je %d.\n", str, lenght(str)); 

    do 
    { 
     scanf("%c", &c); 
     str[i++] = c; 
    } while (c != '\n'); 

    str[i - 1] = 0; 
    printf("The rest: '%s'\n", str); //Rest lenght 
    printf("The rest lenght: %d.", lenght(str)); 
    return 0; 
} 
+1

'* FYI *:' scanf'呼び出しでバッファオーバーフローを防ぐには、読み取れる文字数を制限してください: 'scanf("%100s "、str);' – pmg

答えて

1

あなたはstrtok()

int i = 0; 
char delim[2] = " "; 
char *c = strtok(str, delim); //space is the delimiter. 
// c points to the first word 
while(c != NULL) 
{ 
    printf(" %s\n",c); 
    c = strtok(str, NULL) //notice this NULL 
    i++; 
    if(i == 2) 
    { 
     //edit your 2nd word 
     //break if you want after this or carry on 
    } 
} 
0

を使用することができますがはstrstr(3)を参照してください。私はそれがあなたが必要とするものだと思う。

関連する問題