我正在为一个赋值创建我自己的字符串字长函数(它至少是分配的一部分),但由于某种原因我得到一个非常奇怪的错误。它应该给我一个字符串中的单词数,但由于某种原因,该值不会被保存。即使我跑它,它说字符串的长度是21,“快乐去幸运符”。有人能告诉我这里有什么问题吗?
#include <stdio.h>
#include <ctype.h> // For the letter checking functions
int findLengthString( char *word){
int i = 0;
int length = 0;
for ( i = 0; word[i] != '\0'; i++){
length++;
}
printf("length is %d", length );
return length;
}
int totalWords(char *str) {
int i = 0;
int total = 0;
int hold = findLengthString(str);
for ( i = 0; i < hold; i++ ) {
if ( str[i] == ' ' || str[i+1] == '\0') {
printf("total is %d", total);
total++;
}
return total;
}
}
int main() {
int hold = 0;
char arr[] = "Happy go lucky charms";
hold = totalWords(arr);
printf("hold is %d", hold);
return 0;
}
答案 0 :(得分:2)
当前的问题是return
处于错误的位置。如果您正确格式化代码,您将清楚地看到错误:
int totalWords(char *str) {
int i = 0;
int total = 0;
int hold = findLengthString(str);
for ( i = 0; i < hold; i++ ) {
if ( str[i] == ' ' || str[i+1] == '\0') {
printf("total is %d", total);
total++;
}
return total; // <<== You return in the loop
}
// You should return here
}
然而,这是一个较小的问题。更大的问题是代码的逻辑是不正确的:它不是计算单词,而是计算空格,因此像"Hello, world!"
这样的字符串将产生10而不是2。
要解决此问题,您需要更改算法,只有在上次增加后看到非空格时才将1
添加到总计中:
int totalWords(char *str) {
int i = 0;
int total = 0;
int hold = findLengthString(str);
int inWord = 0;
for ( i = 0; i < hold; i++ ) {
if ( str[i] == ' ' || str[i+1] == '\0') {
total+= inWord;
inWord = 0;
} else {
inWord = 1;
}
}
printf("total is %d", total);
return total;
}
答案 1 :(得分:1)
#include <stdio.h>
int totalWords(char str []){
int i = 0;
int total = 0;
int hold = strlen(str);
for(i = 0; i&lt; hold; i ++){
if ( str[i] == ' ' || str[i+1] == '\0') {
printf("total is %d\n", total);
total++;
}
}
return total;
}
int main(){
int hold = 0;
char arr[] = "Happy go lucky charms";
hold = totalWords(arr);
printf("hold is %d", hold);
返回0; }