gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
std::string a,剔除a中的空格
- User
std::string a,剔除a中的空格
- Assistant
你可以通过以下几种方式来从字符串中剔除空格:
使用
std::remove和erasecpp#include <iostream> #include <string> #include <algorithm> int main() { std::string a = "例 子 字 符 串"; // 使用 std::remove 和 erase 去除空格 a.erase(std::remove(a.begin(), a.end(), ' '), a.end()); std::cout << a << std::endl; // 输出: 例子字符串 return 0; }使用循环和条件判断
cpp#include <iostream> #include <string> int main() { std::string a = "例 子 字 符 串"; std::string result; // 遍历字符串, 如果不是空格就添加到结果字符串中 for (char c : a) { if (c != ' ') { result += c; } } std::cout << result << std::endl; // 输出: 例子字符串 return 0; }