指针实现统计单词个数C语言
时间: 2024-03-09 22:41:18 浏览: 24
以下是使用指针实现统计单词个数的C语言代码:
```c
#include <stdio.h>
#include <ctype.h>
#define MAX_WORD_LEN 100
int get_word(char *word, int max_len);
int main() {
char word[MAX_WORD_LEN];
int count = 0;
while (_word(word, MAX_WORD_LEN) != EOF) {
count++;
}
printf("单词个数为:%d\n", count);
return 0;
}
int get_word(char *word, int max_len) {
int c;
char *w = word;
while ((c = getchar()) != EOF && !isalpha(c)) {
// 跳过非字母字符
}
if (c == EOF) {
return EOF;
}
*w++ = c;
while (--max_len > 0) {
if (!isalnum(c = getchar())) {
break;
}
*w++ = c;
}
*w = '\0';
return word[0];
}
```
相关问题
c语言指针编写统计一个字符串中单词的个数
要统计一个字符串中单词的个数,你可以使用指针来遍历字符串,并根据空格或其他分隔符判断单词的边界。下面是一个示例代码:
```c
#include <stdio.h>
int countWords(const char* str) {
int count = 0;
int isWord = 0; // 标记当前是否在单词中
while (*str != '\0') {
if (*str == ' ' || *str == '\t' || *str == '\n' || *str == '\r') {
// 当前字符为空格或制表符或换行符或回车符,表示单词结束
isWord = 0;
} else if (!isWord) {
// 当前字符不是空格或制表符或换行符或回车符,且上一个字符是空格或制表符或换行符或回车符,表示进入一个新的单词
isWord = 1;
count++;
}
str++;
}
return count;
}
int main() {
const char* str = "Hello world! How are you?";
int wordCount = countWords(str);
printf("Number of words: %d\n", wordCount);
return 0;
}
```
在上面的代码中,`countWords`函数接受一个字符指针作为参数,并使用指针遍历字符串。它使用`isWord`变量来标记当前是否在单词中。当遇到空格、制表符、换行符或回车符时,将`isWord`设为0表示单词结束。当遇到非空格、制表符、换行符或回车符的字符,并且上一个字符是空格、制表符、换行符或回车符时,将`isWord`设为1表示进入一个新的单词,并且单词计数器`count`加1。最后,返回单词的个数。
在`main`函数中,我们定义了一个字符串,并调用`countWords`函数来统计该字符串中的单词个数,并将结果打印出来。
请注意,这里的分隔符仅包括空格、制表符、换行符和回车符。如果你的需求中还包括其他分隔符,你需要相应地修改代码来适应你的需求。
c语言输入句子统计单词
以下是一个简单的C语言程序,可以实现输入句子并统计单词的功能:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char sentence[100];
int word_count = 0;
printf("请输入一个句子:");
fgets(sentence, 100, stdin);
// 使用 strtok 函数分割句子,统计单词数
char *word = strtok(sentence, " ");
while (word != NULL) {
word_count++;
word = strtok(NULL, " ");
}
printf("该句子中共有 %d 个单词。\n", word_count);
return 0;
}
```
该程序使用了标准库函数 `fgets` 和 `strtok`,前者用于从标准输入中读入句子,后者则用于分割句子并统计单词数。具体而言,`strtok` 函数的第一个参数为需要分割的字符串,第二个参数为分割符,返回值为分割出的第一个单词的指针。每次调用 `strtok` 函数时,它会自动从上一次结束的位置开始继续分割,直到整个字符串都被分割完为止。