我是 C 的新手,我正在尝试编写一个程序,它接受两个字符串文字,在第一个字符串中找到最长的单词,并将其与第二个字符串进行比较。如果第二个字符串(称为“expected”)确实等于第一个,它会打印一条成功消息,如果不是,它会打印实际最长的单词、预期的字符串和原始字符串。
这里有许多其他帖子也有类似的问题,但据我所知,这些归结为添加的 \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
...但它仍然失败。
最佳答案
您正在调用 strncmp()
,它在相同的字符串上返回零,但您正在 bool 上下文中对其进行评估,其中零为假,因此它落入 else 分支。
此外,考虑使用 strlen()
来找出字符串的长度。
关于c - 在 strtok() -C 的输出上使用 strcmp(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39907392/