string和char数组分别输入空格的办法

如果定义了 string类型字符串

string a;
getline(cin,a);

如果定义了char字符串

chra a[10];
cin.getline(a,10);

函数详细用法请自行查询

在C++中,可以通过多种方法删除`std::string`中的空格。以下是几种常见的方法: ### 方法一:使用`erase``remove`函数 ```cpp #include <iostream> #include <string> #include <algorithm> int main() { std::string str = "This is a sample string with spaces."; // 使用removeerase函数删除空格 str.erase(std::remove(str.begin(), str.end(), ' '), str.end()); std::cout << str << std::endl; // 输出: Thisisasamplestringwithspaces. return 0; } ``` ### 方法二:使用`std::copy_if`函数 ```cpp #include <iostream> #include <string> #include <algorithm> #include <cctype> int main() { std::string str = "This is a sample string with spaces."; std::string result; // 使用std::copy_if函数删除空格 std::copy_if(str.begin(), str.end(), std::back_inserter(result), [](char c) { return c != ' '; }); std::cout << result << std::endl; // 输出: Thisisasamplestringwithspaces. return 0; } ``` ### 方法三:使用循环`std::string::find`函数 ```cpp #include <iostream> #include <string> int main() { std::string str = "This is a sample string with spaces."; std::string result; for (size_t i = 0; i < str.length(); ++i) { if (str[i] != ' ') { result += str[i]; } } std::cout << result << std::endl; // 输出: Thisisasamplestringwithspaces. return 0; } ``` ### 方法四:使用`std::regex`库 ```cpp #include <iostream> #include <string> #include <regex> int main() { std::string str = "This is a sample string with spaces."; // 使用正则表达式删除空格 str = std::regex_replace(str, std::regex("\\s+"), ""); std::cout << str << std::endl; // 输出: Thisisasamplestringwithspaces. return 0; } ``` 这些方法都可以有效地删除`std::string`中的空格。选择哪种方法取决于具体的需求偏好。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值