如何将字符串转换为大写。我从谷歌上找到的例子只涉及字符。
当前回答
使用c++ 11和toupper()的简单解决方案。
for (auto & c: str) c = toupper(c);
其他回答
这个c++函数总是返回大写字符串…
#include <locale>
#include <string>
using namespace std;
string toUpper (string str){
locale loc;
string n;
for (string::size_type i=0; i<str.length(); ++i)
n += toupper(str[i], loc);
return n;
}
尝试toupper()函数(#include <ctype.h>)。它接受字符作为参数,字符串是由字符组成的,所以你必须遍历每个单独的字符,当它们放在一起组成字符串时
#include <algorithm>
#include <string>
std::string str = "Hello World";
std::transform(str.begin(), str.end(),str.begin(), ::toupper);
struct convert {
void operator()(char& c) { c = toupper((unsigned char)c); }
};
// ...
string uc_str;
for_each(uc_str.begin(), uc_str.end(), convert());
注意:顶部解决方案的几个问题:
21.5以空结束的序列实用程序 这些头文件的内容应该与标准C库头文件相同<ctype.h>, <wctype.h>, <string.h>, <wchar.h>,和<stdlib.h>[…]
这意味着cctype成员很可能是不适合在标准算法中直接使用的宏。 同一个例子的另一个问题是,它没有强制转换实参,也没有验证它是非负的;这对于使用纯char符号的系统尤其危险。(原因是:如果这是作为一个宏实现的,它可能会使用一个查找表和你的参数索引到那个表。负指数会给你UB。)
不确定是否有内置功能。试试这个:
包括ctype.h或cctype库,以及stdlib.h作为预处理器指令的一部分。
string StringToUpper(string strToConvert)
{//change each element of the string to upper case
for(unsigned int i=0;i<strToConvert.length();i++)
{
strToConvert[i] = toupper(strToConvert[i]);
}
return strToConvert;//return the converted string
}
string StringToLower(string strToConvert)
{//change each element of the string to lower case
for(unsigned int i=0;i<strToConvert.length();i++)
{
strToConvert[i] = tolower(strToConvert[i]);
}
return strToConvert;//return the converted string
}
推荐文章
- 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