如何将字符串转换为大写。我从谷歌上找到的例子只涉及字符。
当前回答
//works for ASCII -- no clear advantage over what is already posted...
std::string toupper(const std::string & s)
{
std::string ret(s.size(), char());
for(unsigned int i = 0; i < s.size(); ++i)
ret[i] = (s[i] <= 'z' && s[i] >= 'a') ? s[i]-('a'-'A') : s[i];
return ret;
}
其他回答
如果你只使用ASCII字符,速度会更快:
for(i=0;str[i]!=0;i++)
if(str[i]<='z' && str[i]>='a')
str[i]+='A'-'a';
请注意,这段代码运行得更快,但只适用于ASCII,不是一个“抽象”的解决方案。
其他UTF8字母的扩展版本:
...
if(str[i]<='z' && str[i]>='a') //is latin
str[i]+='A'-'a';
else if(str[i]<='я' && str[i]>='а') //cyrillic
str[i]+='Я'-'я'
else if(str[i]<='ω' && str[i]>='α') //greek
str[i]+='Ω'-'ω'
//etc...
如果您需要完整的UNICODE解决方案或更传统和抽象的解决方案,请寻找其他答案并使用c++字符串的方法。
我用这个解。我知道你不应该修改数据区域....但我认为这主要是缓冲区溢出错误和空字符....大写字母就不一样了。
void to_upper(const std::string str) {
std::string::iterator it;
int i;
for ( i=0;i<str.size();++i ) {
((char *)(void *)str.data())[i]=toupper(((char *)str.data())[i]);
}
}
我的解决方案(清除第6位):
#include <ctype.h>
inline void toupper(char* str)
{
while (str[i]) {
if (islower(str[i]))
str[i] &= ~32; // Clear bit 6 as it is what differs (32) between Upper and Lowercases
i++;
}
}
使用lambda。
std::string s("change my case");
std::locale locale;
auto to_upper = [&locale] (char ch) { return std::use_facet<std::ctype<char>>(locale).toupper(ch); };
std::transform(s.begin(), s.end(), s.begin(), to_upper);
Boost字符串算法:
#include <boost/algorithm/string.hpp>
#include <string>
std::string str = "Hello World";
boost::to_upper(str);
std::string newstr = boost::to_upper_copy<std::string>("Hello World");
推荐文章
- decltype(auto)的一些用途是什么?
- Shared_ptr转换为数组:应该使用它吗?
- Printf与std::字符串?
- 禁用复制构造函数
- 不区分大小写的“in”
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 只接受特定类型的c++模板
- 如何在PHP中截断字符串最接近于一定数量的字符?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- Ruby数组到字符串的转换
- c++ 11中的递归lambda函数
- 在c++中指针使用NULL或0(零)吗?
- 为什么在Java和。net中不能修改字符串?
- 在c++中,如何将int值附加到字符串中?
- 如何创建一个日期对象从字符串在javascript