修改c字符串 [英] Modifying a c string
问题描述
我试图实现 tolower(char *)
函数,但我遇到访问冲突错误。我知道这是因为编译器将字符串字面量存储在只读存储器中。这是真的?
以下是一些代码:
I'm trying to implement tolower(char *)
function, but I get access violation error. I came to know that this is because to compiler stores string literals in a read-only memory. Is this true?
Here's some code:
char* strToLower(char *str)
{
if(str == nullptr)
return nullptr;
size_t len = strlen(str);
if(len <= 0)
return nullptr;
for(size_t i = 0; i < len; i++)
*(str+i) = (char)tolower(*(str+i));//access violation error
return str;
}
int main()
{
char *str = "ThIs Is A StRiNgGGG";
cout << strToLower(str) << endl;
system("pause");
return 0;
}
如果这是真的,我应该如何实现这样的功能? p>
If this is true, how am I supposed to implement such function?
推荐答案
是的,这是真的。您不能修改字符串文字。事实上,如果你的编译器不是从1922年,它将阻止你甚至获得一个非 - const
指向一个字符串字面量的第一位。
Yes, it's true. You cannot modify a string literal. In fact, if your compiler were not from 1922 it would have prevented you from even obtaining a non-const
pointer to a string literal in the first place.
你没有说明你的目标,所以当你问我应该如何实现这样的功能时,你不清楚你想要做什么。但您可以对字符串文字进行复制,以获取您自己的字符串,然后按照以下步骤进行修改:
You didn't state your goals, so when you ask "how am I supposed to implement such function" it's not really clear what you want to do. But you can make a copy of the string literal to get your own string, then modify that as you please:
// Initialises an array that belongs to you, by copying from a string literal
char str[] = "ThIs Is A StRiNgGGG";
// Obtains a pointer to a string literal; you may not modify the data it points to
const char* str = "ThIs Is A StRiNgGGG";
// Ancient syntax; not even legal any more, because it leads to bugs like yours
char* str = "ThIs Is A StRiNgGGG";
当然,由于这是C ++,你不应该首先使用C字符串:
Of course, since this is C++, you should not be using C-strings in the first place:
std::string str("ThIs Is A StRiNgGGG");
这篇关于修改c字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!