c - 为什么我的字符串末尾总是有多余的字符?

标签 c string

我有字符串“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/

相关文章:

c - 在 C 中使用整型全局变量指针初始化全局变量

c - 用新字符串替换字符串模式

java - 在 Java 8 中,有什么优雅的方法可以从字符串中删除某些重复的单词

android - 如何从 SimpleCursorAdapter 的选定项中获取字符串?

string - 如何将一串数字转换为数字向量?

c - 强制程序使用输入字符串调用 C 函数

c - 如何在C语言中将文本文件读取到结构数组中

c - 使用 Pthreads 的同步问题

c - 开关和指针的使用方式,我很陌生

swift - 从字符串中删除停用词而不修剪 Swift 中的其他词