我有一个字符串,可能包含数字以及大写和小写字母。我需要将所有大写字母转换为小写,反之亦然。怎么会这样呢?
答案 0 :(得分:10)
这是一种没有提升的方法:
#include <string>
#include <algorithm>
#include <cctype>
#include <iostream>
char change_case (char c) {
if (std::isupper(c))
return std::tolower(c);
else
return std::toupper(c);
}
int main() {
std::string str;
str = "hEllo world";
std::transform(str.begin(), str.end(), str.begin(), change_case);
std::cout << str;
return 0;
}
答案 1 :(得分:7)
迭代字符串并使用isupper()
确定每个字符是否为大写。如果它是大写的,请使用tolower()
将其转换为小写。如果它不是大写,请使用toupper()
将其转换为大写。
答案 2 :(得分:1)
您可以遍历字符串并在每个字母字符中添加或减去相应的数字,以便将ASCII值解析为相反的ASCII值。
答案 3 :(得分:0)
char *str = "this is a test string";
while(*str != '\0') {
if(*str <= 'Z' && *str >= 'A') {
*str += 32;
}
if(*str >= 'a' && *str <= 'z') {
*str -= 32;
}
str++;
}
根本不安全,只是给你一个想法。 这可能对这项作业很有帮助:
答案 4 :(得分:0)
您也可以翻转32位:因此使用ASCII字符:
char flipcase(char x)
{
if( ::isalpha(x) )
{
return x ^ 32;
}
}
您也可以使用表格。然后创建一个静态表
char flipcase( char x )
{
return fliptable[x];
}
后一种方法具有能够用于外来字符集的优点,只要它们不是多字节的 - 它将不起作用。您可以使用您正在使用的任何字符集为wchar_t字符创建类似的表。如果您的角色的大小不超过2,则存储表需要少量内存使用,尽管它对UTF-32使用太多而且查找时间很简单。当然,实际上你会为每个角色存储一个小结构及其特征。
使用上述任一方法,您将使用std :: transform。
现在真正聪明的一点:std :: transform可以使用类(仿函数)以及普通函数。因此,对于多字节字符,只要替换字符始终具有相同的第一个元素,我们就可以存储状态。如果不是这种情况,那么transform将不适用于常规迭代器。但是,您可以编写一个自定义迭代器来处理多字节字符串,这些字符串一次迭代一个可打印字符(迭代器必须取消引用代表符号的多字节字符)。
答案 5 :(得分:0)
image
答案 6 :(得分:0)
执行此操作的标准 C++ 方法如下:
std::string lower = "this is my string to be uppercased";
std::locale loc; //get the locale from the system.
auto facet = std::use_facet<std::ctype<char>>(loc);
facet.toupper(&lower[0], &lower[0] + lower.length()); //they didn't provide a C++ iterator interface, so pointer arithmetic it is.
std::cout << lower << std::endl;
这个输出:
THIS IS MY STRING TO BE UPPERCASED
还有一个 facet.toupper()
用于处理小写到大写的转换,facet.widen
用于从 char 转换为 wchar_t,还有 facet.narrow
用于将 wchar_t 转换为 char。