如何解决C ++ TitleCase char *函数在每个Google C ++测试结束时返回“ CCCCC”
我正在尝试创建一个char* toTitleCase(char* text)
函数,使文本中的每个单词都以大写字母开头。
这是我当前的代码:
char* toTitleCase(char* text)
{
char* arr = new char[strlen(text) + 1];
for (int i = 0; *(text + i) != '\0'; i++)
arr[i] = *(text + i);
// Example: arr is Now "salut. ce mai faciCCCCCCCCCC"
for(int i = 0 ; arr[i] != '\0' ; i++)
{
// Make the first letter capital if it isn't.
if (i == 0 && (arr[i] >= 97 && arr[i] <= 122))
arr[i] = arr[i] - 32;
// Check for a blank space. If found,check the next char and make it capital.
else if (arr[i] == ' ' && (arr[i + 1] >= 97 && arr[i + 1] <= 'z'))
arr[i+1] = arr[i+1] - 32;
}
// Example: arr is : "Salut. Ce Mai FaciCCCCCCCCCC"
return arr;
delete[] arr;
// Example Google C++ Test :
//Expected: "Salut. Ce Mai Faci"
// Got : "Salut. Ce Mai FaciCCCCCCCCCC"
}
我的问题:
- 如果我专门分配了文本的长度+ 1,为什么最后得到“ CCCCC”?
- 我该如何解决这个问题?
解决方法
我专门分配了文本的长度+ 1
有个提示-the length of the text
是什么?
更改此:
for (int i = 0; *(text + i) != '\0'; i++)
arr[i] = *(text + i);
对此:
for (int i = 0; *(text + i) != '\0'; i++)
printf("%c",*(text + i));
它将回答您的问题
换句话说,您没有使用空字符正确终止输入字符串。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。