在C++中,如果你想忽略字符串中的空格,可以使用以下幾種方法:
std::cin.ignore()
函數(shù):這個函數(shù)可以讀取并忽略輸入流中的指定數(shù)量的字符。例如,如果你想忽略一行中的所有空格,你可以這樣做:#include <iostream>
#include <limits>
int main() {
std::string input;
std::getline(std::cin, input);
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// 現(xiàn)在input中不包含空格
}
std::istringstream
類:這個類可以將一個字符串轉(zhuǎn)換為一個輸入流,你可以使用它的>>
運算符來讀取字符串中的單詞,這樣就可以自動忽略空格了。例如:#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string input = "Hello World";
std::istringstream iss(input);
std::string word;
while (iss >> word) {
// 現(xiàn)在word中不包含空格
std::cout << word << std::endl;
}
}
<regex>
庫提供了對正則表達式的支持,你可以使用它來匹配并刪除字符串中的空格。例如:#include <iostream>
#include <string>
#include <regex>
int main() {
std::string input = "Hello World";
std::string output = std::regex_replace(input, std::regex("\\s"), "");
// 現(xiàn)在output中不包含空格
std::cout << output << std::endl;
}