试图编辑问题以便更清楚,这里的代码应该打印字符串及其长度,但不是打印12的长度,而是只打印1.参数(char * s)无法更改并且while循环的条件必须基于s = s + 1
增量,但是对于长度,它仍然必须返回i。
#include<stdio.h>
#include<string.h>
#define CADENA_PRUEBA "Hola a todos"
int longitud_string(char *s){
int i;
i=0;
while(*s != '\0')
s = s + 1;
i++;
return i;
}
int main(void){
char string1[] = CADENA_PRUEBA;
printf("cadena: %s\n", string1);
printf("longitud cadena: %d\n", longitud_string(string1));
return 0;
}
它只打印1
int longitud_string(char *s){
int i;
i=0; // Set i = 0
while(*s != '\0')
s = s + 1;
i++; // Set i = 1
return i; // return i (1)
}
你可能想要的是:
int longitud_string(char *s)
{
int i = 0;
while(*s != '\0')
{ // Need brace here
s = s + 1;
i++; // Increment both in the loop
} // Close brace here.
return i;
}
但我们可以像这样简化它:
int longitud_string(char *s)
{
int i = 0;
while(s[i] != '\0') {
i++;
}
return i;
}
首先,让我优化您的代码
int longitud_string(const char *s)
{
int i = 0; // Initalize it with 0
while(*s) // No need to check for '\0'
s++; // Same as: s = s + 1 or s += 1
i++; // Here you increament i only once cause you're outside the scopes of while() loop
return i; // Returns i value which is equal to 1 cause it incremented only 1 time.
}
你错过了while循环中的范围,所以你的代码应该是
int longitud_string(const char *s)
{
int i = 0; // Initalize it with 0
while(*s) // No need to check for '\0'
{
s++; // Same as: s = s + 1 or s += 1
i++; // Incrementing every iteration of the loop, now it's working.
}
return i; // Returns the number of iteration of the loop which is equal to the length of (s)
}
现在我们解决了问题,但我们可以更优化它...
int getLength(const char* String)
{
int i = 0;
while(String != NULL && *String++ && ++i);
return i;
}