将字符串转换为全部大写 - C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8302797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:20:18  来源:igfitidea点击:

Convert String into all uppercase - C++

c++stringsorting

提问by jordaninternets

I am having trouble turning strings to uppercase for an alphabetical sort. My program actually begins to slow down and freeze after the third set of words. What am I doing wrong?

我无法将字符串转换为大写字母以进行字母排序。在第三组单词之后,我的程序实际上开始变慢和冻结。我究竟做错了什么?

string iName = list[i]->GetLastName(); // This just returns a string of a name
string jName = list[j]->GetLastName();

for(unsigned int k = 0; k < iName.length(); k++)
  {
    iName[k] = toupper(iName[k]);
  }

for(unsigned int l = 0; l < jName.length(); l++)
  {
    iName[l] = toupper(jName[l]);
  }

回答by Hauleth

Use STL algorithmlibrary:

使用 STLalgorithm库:

std::for_each(iName.begin(), iName.end(), std::toupper);

or (suggested by @Kerrek SB)

或(由@Kerrek SB建议)

std::transform(s.begin(), s.end(), s.begin(), std::toupper);

回答by Keith Nicholas

as others said, you mixed iname and jname.... and why did you do this?

正如其他人所说,你混合了 iname 和 jname ......你为什么这样做?

Because you copy pasted!

因为你复制粘贴了!

So, a good early lesson in programming is to try and avoid copy paste! instead try and create functions.....

所以,编程的一个很好的早期教训是尽量避免复制粘贴!而是尝试创建函数.....

in your case...

在你的情况...

void stringToUpper(string &s)
{
   for(unsigned int l = 0; l < s.length(); l++)
  {
    s[l] = toupper(s[l]);
  }
}

then you can do

那么你可以做

stringToUpper(iName);
stringToUpper(jName);

This approach redues a LOT of errors related to copy pasting and in general, helps make your programs a lot more modular

这种方法减少了很多与复制粘贴相关的错误,并且通常有助于使您的程序更加模块化

回答by pedorro

The standard suggests that you should not use [] operator on string to modify it's contents. string is designed as an immutable object and your code is breaking that standard. So I guess the answer is that it's hard to say what may be happening because you are using the class in a way in which it was not designed. It could be messing up some internal index or something else. We don't know what the string class may be doing internally.

该标准建议您不应在字符串上使用 [] 运算符来修改其内容。string 被设计为不可变对象,而您的代码正在打破该标准。所以我想答案是很难说可能会发生什么,因为您正在以一种非设计的方式使用该类。它可能会搞乱一些内部索引或其他东西。我们不知道字符串类可能在内部做什么。

That said, it seems like it should work :)

也就是说,它似乎应该工作:)