我有字符串“helLo, wORld!”我希望我的程序将其更改为“Hello, World!”。我的程序运行正常,字符已正确更改,但我在感叹号后不断收到额外的字符。我可能做错了什么?
void normalize_case(char str[], char result[])
{
if (islower(str[0]) == 1)
{
result[0] = toupper(str[0]);
}
for (int i = 1; str[i] != '\0'; i++)
{
if (isupper(str[i]) == 1)
{
result[i] = tolower(str[i]);
}
else if (islower(str[i]) == 1)
{
result[i] = str[i];
}
if (islower(str[i]) == 0 && isupper(str[i]) == 0)
{
result[i] = str[i];
}
if (str[i] == ' ')
{
result[i] = str[i];
}
if (str[i - 1] == ' ' && islower(str[i]) == 1)
{
result[i] = toupper(str[i]);
}
}
}
最佳答案
你不是空终止 result
所以当你打印出来时它会继续直到找到空值。如果将 i
的声明移动到 for
循环之前:
int i ;
for ( i = 1; str[i] != '\0'; i++)
你可以添加:
result[i] = '\0' ;
在 for
循环之后,这是假设 result
足够大。
关于c - 为什么我的字符串末尾总是有多余的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16953115/