java在文本中读取单词_从文本文件中查找不包含元音的单词

此代码采用不同的方法 . 它将使用 fgets 读取每一行,然后使用 sscanf 查找字符串中的每个单词 . 这应该处理单词之间的制表符和空格 . 如果行太长,它还确保我们不会溢出输入缓冲区 . 如果一行太长 fgets 将用它找到的内容填充字符串缓冲区 . 我们必须确保跳过所有剩余的字符直到换行符 \n ,这样我们才能正确找到下一行的开头 .

该代码还修复了一些问题 . 字符串长度在原始海报(OP)代码中设置在错误的位置 . 按位 | 已更改为逻辑或 || 并且代码已被修改以搜索单词中的元音并设置标志(如果找到一个) . 如果一个单词不包含元音,则将其打印出来 . 代码应该在C89编译器(或更高版本)下运行 .

有关使用 sscanf 解析字符串的信息可以在here找到

#include

#include

#include

#define MAX_LINE_LENGTH 512

#define MAX_WORD_LENGTH MAX_LINE_LENGTH

int

main()

{

FILE *f = fopen("test.txt", "r");

char line[MAX_LINE_LENGTH];

/* Process each line in the file */

while (fgets(line, MAX_LINE_LENGTH, f)) {

char word[MAX_WORD_LENGTH];

char *curline = line; /* current pointer in the string we are processing */

int charsread;

/* If we read maximum number of characters then make

* sure we flush the rest of the line up until the newline so

* the next pass will start at the beginning of the next line */

if ((line[MAX_LINE_LENGTH - 1] != '\0')

&& (line[MAX_LINE_LENGTH - 1] != '\n')) {

while (fgetc(f) != '\n');

}

/* Scan for each word in the string we read */

while (sscanf(curline, "%s%n", word, &charsread) > 0) {

int i;

int wordlen = strlen(word);

int vowelfnd = 0; /* vowelfnd set as false */

for (i = 0; i < wordlen; i++) {

if (word[i] == 'a' || word[i] == 'e' ||

word[i] == 'i' || word[i] == 'o' ||

word[i] == 'u' || word[i] == 'y') {

/* Set vowelfnd to true */

vowelfnd = 1;

break;

} /* end of else */

} /* end of for loop */

/* If we didn't find a vowel print word */

if (!vowelfnd)

printf("%s ", word);

/* Advance past the word we just read in the

* string buffer */

curline += (charsread);

}

} /* end of while loop */

return 0;

} /* end of main */

从字符串(我将使用的那个)中读取单词的更高级方法是使用 strtok C函数,您可以找到更多关于here的函数 . 该链接还包含一些示例代码,可用于搜索字符串中的单词 . strtok的一个优点是,您可以轻松指定其他单词分隔符,如句点,问号等 .

在OP发布问题后,他们又增加了一条信息 . 所提供的所有解决方案都假设一行有多个单词,但情况并非如此 . 最简单的解决方案是修复原始中的错误,只需:

#include

#include

#include

#define MAX_LENGTH 64

int

main()

{

FILE *f = fopen("test.txt", "r");

char word[MAX_LENGTH];

int i;

int length;

while (fgets(word, MAX_LENGTH, f)) {

int vowelfnd = 0; /* Vowel found false */

/* Remove the end of line character(s) */

strtok(word, "\n");

length = strlen(word);

for (i = 0; i < length; i++) {

if (word[i] == 'a' || word[i] == 'e' || word[i] == 'i' ||

word[i] == 'o' || word[i] == 'u' || word[i] == 'y') {

vowelfnd = 1; /* Vowel found true */

break;

} /* end of if statement */

} /* end of for loop */

if (vowelfnd)

printf("%s ", word);

} /* end of while loop */

return 0;

} /* end of main */

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值