首页 > 解决方案 > 不打印句子前三个单词的指针

问题描述

没有任何代码,我被困在如何解决这个问题上。我希望代码让用户输入一个长句子,然后输入一个不打印任何给定句子的前 3 个单词的指针。对我来说棘手的部分是 char 在开始时没有定义,所以我不能只删除我想要的单词。

示例:

您好,我需要有关此代码的帮助

帮助使用此代码

标签: c

解决方案


沿着这条线走,数一数空格的数量

#include <stdio.h>
#define INPUT_BUFFER_SIZE 256

int main(void) {
    // Reading user input
    char buf[INPUT_BUFFER_SIZE];
    fgets(buf, INPUT_BUFFER_SIZE, stdin);

    int words_to_skip = 3;
    char* current_pos = &buf[0];

    for (; words_to_skip > 0 && *current_pos != 0; current_pos++) {
        // If current char is space - then we reached the next word
        if (*current_pos == ' ') {
            words_to_skip--;
        }
    }

    if (*current_pos == 0) {
        printf("Not enough words entered\n");
    } else {
        printf("%s", current_pos);
    }
}

或者,使用内置strchr()函数:

#include <stdio.h>
#include <string.h>
#define INPUT_BUFFER_SIZE 256

int main(void) {
    // Reading user input
    char buf[INPUT_BUFFER_SIZE];
    fgets(buf, INPUT_BUFFER_SIZE, stdin);

    int words_to_skip = 3;
    char* current_pos = &buf[0];

    while (current_pos != 0 && *current_pos != 0 && words_to_skip > 0) {
        current_pos = strchr(current_pos, ' ');
        if(current_pos != 0) {
            current_pos++;
        }
        words_to_skip--;
    }
    if (current_pos == 0) {
        printf("Not enough words entered\n");
    } else {
        printf("%s\n", current_pos);
    }
}

推荐阅读