如果给我一个字符串,我需要大写或标题字符串。例如:
您的代码存在一些问题。以下是您的代码的修改版本,工作正常。这里:
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以防止超出范围访问字符串。
使用字符串流首先拆分所有单词,以便您可以使用向量轻松完成此操作。这是Title
函数的一个实现:
std::string Title(const std::string &str) {
std::vector<string>words;
words.clear();
std::string res = str, std::ans = "";
// It's better to pass the string AFTER you convert it all lowercase. Or you can only work with the capitalized characters:
for(int i = 0; i < res.size(); ++i){
if(res[i] >= 'A' && res[i] <= 'Z'){
res[i] = tolower(res[i]);
}
}
istringstream ss(res); // We push the modified string into a stringstream.
do{
res = "";
ss >> res;
words.push_back(res); // We split the string at " " and push each word in the vector.
} while(ss)
for(int i = 0; i < words.size(); ++i){
res = words[i];
res[0] = toUpper(res[0]); // For each word, we capitalize it
ans += res; // We add the word to our return string.
if(i < words.size() - 1){
ans += " "; // If this is not the last word, add a space
}
}
return ans;
}
至于大写,您可以这样做:
std::string Capitalize(const std::string &&str){
std::string res = str;
res[0] = toupper(res[0]);
for(int i = 1; i < res.size(); ++i){
if(res[i] >= 'A' && res[i] <= 'Z'){
res[i] = tolower(res[i]); // converting if only an uppercase character.
}
}
return res; // If you pass a reference, the original will be modified so no return required.
}