c - 不打印句子前三个单词的指针
问题描述
没有任何代码,我被困在如何解决这个问题上。我希望代码让用户输入一个长句子,然后输入一个不打印任何给定句子的前 3 个单词的指针。对我来说棘手的部分是 char 在开始时没有定义,所以我不能只删除我想要的单词。
示例:
您好,我需要有关此代码的帮助
帮助使用此代码
解决方案
沿着这条线走,数一数空格的数量
#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);
}
}
推荐阅读
- java - Java List.add() 方法添加一个可修改的对象
- php - 如何在laravel中获取碳日期的季度数
- javascript - StatusBarItem 的注册命令
- r - 日期框架未正确解析 H:M:S
- ios - 如何在移动模拟器中测试地图航向功能?
- r - 如何通过posixct将09-Oct-2017这样的日期转换为09-11-2017?
- django - Django 更改模型选择的查询集
- azure-logic-apps - (Azure 逻辑应用):如何从授权应用获取访问令牌
- javascript - bug:ReferenceError: self 未定义 exif-js
- oracle - 数字中尾随零的数量