基于 Qt 的 addSlashes 版本等效
我刚刚编写了一个基于 Qt 的 php addSlashes 函数,我不会看到任何改进,对其提出建议。我计划使用此函数来填充一个包含数百个 insert
查询的文件,更具体地说,我将创建 php 数据库转储 之类的。
QString addSlashes(QString str)
{
QString newStr;
for(int i=0;i<str.length();i++)
{
if(str[i] == '\0')
{
newStr.append('\\');
newStr.append('0');
}
else if(str[i] == '\'')
{
newStr.append('\'');
}
else if(str[i] == '\"')
{
newStr.append('\"');
}
else if(str[i] == '\\')
{
newStr.append('\\');
}
else
newStr.append(str[i]);
}
return newStr;
}
I just wrote a Qt based php addSlashes function like, I wont to see any improvements, suggestions to it. I am planing to use this function to fill a file with hundred of insert
query, to be more specific, I am going to create php database dump like.
QString addSlashes(QString str)
{
QString newStr;
for(int i=0;i<str.length();i++)
{
if(str[i] == '\0')
{
newStr.append('\\');
newStr.append('0');
}
else if(str[i] == '\'')
{
newStr.append('\'');
}
else if(str[i] == '\"')
{
newStr.append('\"');
}
else if(str[i] == '\\')
{
newStr.append('\\');
}
else
newStr.append(str[i]);
}
return newStr;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想我会将数据与代码分开,例如:
当然,您可能更喜欢使用
QMap
而不是std::map
。这会改变一些东西的拼写方式,但不会改变基本思想。或者,由于每个“特殊”输出只是前面带有反斜杠的原始字符,因此您可以只使用需要反斜杠的
std::set
字符:鉴于涉及的字符数量很少,您可以也可以使用
std::bitset
或std::vector
之类的东西。我们讨论的是 32 字节的存储(假设您只关心 256 个字符)。当你认真思考时,地图/集合只是被用作稀疏数组,但如果你只在一个(甚至几个)地方使用它,那么毫无疑问你会节省更多空间(在代码中)使用数组而不是使用集合/映射保存(在数据中)。I think I'd separate the data from the code, something like:
You may, of, course prefer to use a
QMap
instead of astd::map
though. That'll change how you spell a few things, but doesn't change the basic idea.Alternatively, since each "special" output is just the original character preceded by a backslash, you could just use an
std::set
of characters that need a backslash:Given the small number of characters involved, you could also use something like an
std::bitset
orstd::vector<bool>
as well. We're talking about 32 bytes of storage (assuming you only care about 256 characters). When you get down to it, the map/set is just being used as a sparse array, but if you're only using it in one (or even a few) places, you'll undoubtedly save more space (in code) by using an array than you save (in data) by using the set/map.