[英]Code that checks if a words from string is a palindrome. Can't recognize words at the end of the phrase
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define NMAX 1000
int main()
{
char line[NMAX];
int palindromo = 1;
FILE*fp;
fp=fopen("input.txt", "r");
if(fp != NULL){
while(fgets(line, NMAX, fp)){
char*word = strtok(line, " ");
while(word != NULL){
palindromo = 1;
int lunghezza = strlen(word);
if((lunghezza>0) && (word[lunghezza-1] == '\n')){
word[lunghezza-1] = '\0';
}
for(int i=0; i<lunghezza; i++){
word[i] = tolower(word[i]);
}
for(int i=0; i<lunghezza/2; i++){
if(word[i] != word[lunghezza-1-i]){
palindromo = 0;
}
}
if(palindromo == 1){
for(int i=0; i<lunghezza; i++){
word[i] = toupper(word[i]);
}
}
puts(word);
word = strtok(NULL, " ");
}
}
}
}
输入文件是这样的:
Anna ha preso otto a scuola. la mamma le ha regalato una spilla in oro e le ha organizzato un giro in kayak
Anche il cane ha avuto in premio un osso lo ha mangiato come un ossesso.
程序唯一不能识别为回文的词是 kayak 和 ossesso(都在字符串的末尾)。
请注意代码和 input.txt 文件是意大利语。
正如@RobMayoff 已经指出的那样,您必须考虑缩短缓冲区中最后一个单词的长度。
您可以通过在对strtok()
的两次调用中使用" \n"
作为分隔符来避免悲伤和编写代码。 function 会破坏SP 和换行符,向后传递指向单个单词的指针。
word = strtok( line, " \n" );
通过这样做,您消除了一些代码(碰巧有错误。)
为了通过两次单独调用strtok()
来避免未来出现错误的机会,可以在一行中重写该操作:
for( char *word = line; (word = strtok( word, " \n" ) ) != NULL; word = NULL )
想一想这个for()
循环,看看它为什么有效。
代码越少(有效)越好。
当word[lunghezza-1] == '\n'
时,您将\n
替换为\0
。 您还需要将lunghezza
减少 1。
if((lunghezza>0) && (word[lunghezza-1] == '\n')){
word[lunghezza-1] = '\0';
--lunghezza;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.