问题描述
我正在尝试创建一个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));
它将回答您的问题
换句话说,您没有使用空字符正确终止输入字符串。