我是C的新手,我试图编写一个带有两个字符串文字的程序,找到第一个中最长的单词,然后将它与第二个字符串进行比较。如果第二个字符串(称为"期望")确实等于第一个字符串,则会打印成功消息,如果不是,则打印实际最长字,预期字符串和原始字符串。
此处还有很多其他帖子存在类似问题,但根据我的理解,\n
添加了\0;
,这些帖子可归结为strtok()
或遗失\0
由于我使用的是硬编码文字,我确信没有拖尾换行符,就像读取输入一样。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
char* currentTok;
static const char* result;
static char* longestTok;
static int testsExecuted = 0;
static int testsFailed = 0;
void testLongestWord();
const char* longestWord();
int totalLength();
int charLength();
int main(int argc, char *argv[]) {
printf("Testing typical cases, including punctuation\n");
testLongestWord("the quick brown foxes jumped over the lazy dogs", "jumped");
//There are other examples, some of which fail, and others don't, though I don't see a pattern
printf("\nTotal number of tests executed: %d\n",testsExecuted);
printf("Number of tests passed: %d\n",(testsExecuted - testsFailed));
printf("Number of tests failed: %d\n",testsFailed);
}
//tests words, prints success/failure message
void testLongestWord(char* line, char* expected){
result = longestWord(line, totalLength(line));
if (strncmp(result, expected,charLength(expected)-1)||totalLength(expected)==0){//the problem spot
printf("Passed: '%s' from '%s'\n",expected, line);
} else {
printf("FAILED: '%s' instead of '%s' from '%s'\n",result, expected, line);
testsFailed++;
}
testsExecuted++;
}
//finds longest word in string
const char *longestWord(char* string, int size){
char tempString[size+10];//extra room to be safe
strcpy(tempString,string);
currentTok = strtok(tempString,"=-#$?%!'' ");
longestTok = "\0";
while (currentTok != NULL){
if (charLength(currentTok)>charLength(longestTok)){
longestTok = currentTok;
}
currentTok = strtok(NULL,"=-#$?%!'' ");
}
return longestTok;
}
int totalLength(const char* string) {
int counter = 0;
while(*(string+counter)) {
counter++;
}
return counter;
}
int charLength(const char* string) {
int counter = 0;
int numChars = 0;
while(*(string+counter)) {
if (isalpha(*(string+counter))){
numChars++;
}
counter++;
}
return numChars;
}
问题是它返回:
FAILED: 'jumped' instead of 'jumped' from 'the quick brown foxes jumped over the lazy dogs'
显然,字符串是相同的,我已经完成了其他测试,以确保它们的长度相同,\0
...但仍然失败。
答案 0 :(得分:2)
你正在调用strncmp()
,它在相等的字符串上返回零,但是你在布尔上下文中对它进行评估,其中零是false,所以它属于else分支。
另外,请考虑使用strlen()
来查找字符串的长度。