gpt4 book ai didi

c++ - 如何大写和标题字符串

转载 作者:行者123 更新时间:2023-11-28 04:19:54 27 4
gpt4 key购买 nike

如果我得到一个字符串,我需要将字符串大写标题。例如:

最佳答案

您的代码存在一些问题。这是您的代码的修改版本,可以正常工作。这里:

std::string Capitalize(const std::string &str) {
std::string Ret;
for (int i = 0; i < str.length(); i++){
char c = str[i];
if (i == 0){
Ret += toupper(c);
}
else if (i != 0){
Ret += (tolower(c));
}
}
return Ret;}

for 循环中的条件需要是 str.length() 而不是 Ret.length() 并且这里:

std::string Title(const std::string &str) {
std::string Ret;
int i=0;
for (int i=0;i<str.size();i++) {
if(!(i==0 && str[i]==' '))
Ret += tolower(str[i]);
}

int size = Ret.length();
for (int i = 0; i < size; i++) {
if (i==0 || Ret[i - 1] == ' ')
{
Ret[i] = toupper(Ret[i]);
}
}
return Ret;}

检查 i 是否为 0 以防止对字符串的越界访问。

关于c++ - 如何大写和标题字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55700196/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com