当您决定从字符串中删除一个字符时,您可以将剩余的字符向左移动一个位置,这很好,但是无论该字符的实际值如何,都可以在该字符开始移动后的位置跳过该字符是。 这就是为什么您在输出中看到不需要的字符的原因。 只需在移位后不增加指针,例如:
#include
#include
#include
void removeIfNotLowercaseOrWhitespace(char *text);
int main()
{
char str[100];
std::cout << "Enter a string: ";
std::cin.getline(str, 100);
removeIfNotLowercaseOrWhitespace(str);
std::cout << "\nOutput after lowerCase():\n";
std::cout << str;
std::system("pause>0");
return 0;
}
void removeIfNotLowercaseOrWhitespace(char *text)
{
while (*text != '\0') {
if (std::islower(*text) || std::isspace(*text)) {
++text;
}
else {
for (char *i = text; *i != '\0'; ++i) {
*i = *(i + 1);
}
}
}
}
但是,话虽如此,这种方法实际上是C的处理方式!
#include
#include
#include
#include
bool isNotLowercaseOrWhitespace(char c);
int main()
{
std::string str;
std::cout << "Enter a string: ";
std::getline(std::cin, str);
str.erase(
std::remove_if(str.begin(), str.end(),
isNotLowercaseOrWhitespace
/* alternatively, in C++11 and later:
[](char c){ return !(std::islower(c) || std::isspace(c)); }
*/
)
);
std::cout << "\nOutput after lowerCase():\n";
std::cout << str;
std::cin.get();
return 0;
}
bool isNotLowercaseOrWhitespace(char c)
{
return !(std::islower(c) || std::isspace(c));
}
或者,创建一个新的std::string ,其中包含要保留的字符的副本,例如:
#include
#include
#include
#include
std::string removeAllNotLowercaseOrWhitespace(const std::string &s);
int main()
{
std::string str;
std::cout << "Enter a string: ";
std::getline(std::cin, str);
str = removeAllNotLowercaseOrWhitespace(str);
std::cout << "\nOutput after lowerCase():\n";
std::cout << str;
std::cin.get();
return 0;
}
std::string removeAllNotLowercaseOrWhitespace(const std::string &str)
{
std::string ret;
ret.reserve(str.size());
for(std::string::const_iterator iter = str.begin(); iter != str.end(); ++iter) {
char c = *iter;
if (std::islower(c) || std::isspace(c)) {
ret.push_back(c);
}
}
/* alternatively, in C++11 and later:
std::copy_if(str.begin(), str.end(), std::back_inserter(ret),
[](char c){ return (std::islower(c) || std::isspace(c)); }
);
*/
return ret;
}