gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
std::string a,将a里所有大写字母转小写字母,并去掉空格
- User
std::string a,将a里所有大写字母转小写字母,并去掉空格
- Assistant
你可以使用C++标准库中的
std::transform函数来把字符串中的所有大写字母转化为小写字母,并使用std::remove函数移除空格。以下是一个实现方法:#include <algorithm> #include <cctype> #include <iostream> #include <string> int main() { std::string a = "HeLLo WoRLD"; // 转换所有大写字母为小写字母 std::transform(a.begin(), a.end(), a.begin(), [](unsigned char c) { return std::tolower(c); }); // 移除所有空格 a.erase(std::remove(a.begin(), a.end(), ' '), a.end()); std::cout << a << std::endl; // 输出: helloworld return 0; }在以上代码中:
std::transform函数用来将字符串a中的每个字符转化为小写字母。std::remove函数用来将a中的所有空格移到字符串的末尾,然后a.erase方法用来删除这些空格。
这样,你就得到了一个全部为小写字母且没有空格的字符串。