阅读量:135
在C++中,如果你想忽略字符串中的空格,可以使用以下几种方法:
- 使用
std::cin.ignore()函数:这个函数可以读取并忽略输入流中的指定数量的字符。例如,如果你想忽略一行中的所有空格,你可以这样做:
#include
#include
int main() {
std::string input;
std::getline(std::cin, input);
std::cin.ignore(std::numeric_limits::max(), '\n');
// 现在input中不包含空格
}
- 使用
std::istringstream类:这个类可以将一个字符串转换为一个输入流,你可以使用它的>>运算符来读取字符串中的单词,这样就可以自动忽略空格了。例如:
#include
#include
#include
int main() {
std::string input = "Hello World";
std::istringstream iss(input);
std::string word;
while (iss >> word) {
// 现在word中不包含空格
std::cout << word>
- 使用正则表达式:C++的
库提供了对正则表达式的支持,你可以使用它来匹配并删除字符串中的空格。例如:
#include
#include
#include
int main() {
std::string input = "Hello World";
std::string output = std::regex_replace(input, std::regex("\\s"), "");
// 现在output中不包含空格
std::cout << output>