Using c++ 14. 我提示用户输入一个包含字母和整数的字符串,并尝试通过 string.erase(( 函数从字符串本身"剥离"整数。
我面临的问题是,当有 2 个或更多连续数字时,函数似乎会擦除第一个数字但删除后者。
例:
input: H23ey Th2e3re St01ack O34verflow
output: H3ey There St1ack O4verflow
我可以通过使用新字符串、循环访问现有字符串并仅添加 isalpha 或 isspace 来以另一种方式做到这一点,但它似乎更混乱。
法典:
string digalpha {};
cout << "Enter string containing both numbers and letters: ";
getline(cin, digalpha);
for (size_t i {}; i < digalpha.size(); i++)
if (isdigit(digalpha.at(i)))
digalpha.erase(i,1);
cout << digalpha << endl;
cout << endl;
return 0;
在第一句话中,你写道你正在使用C++14。
在"更现代"的C++建议使用算法。所以通常你不会使用 C 样式 For 循环。
随处可见的标准方法是 erase
与std::remove_it
相结合 .您将在许多示例中找到此构造。
请考虑使用这样的解决方案而不是 for 循环。
您甚至可以使用 std::copy_if
将输出包含在算法中。
请看:
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
std::string test1{ "H23ey Th2e3re St01ack O34verflow" };
std::string test2{ test1 };
// C++ standard solution for erasing stuff from a container
test1.erase(std::remove_if(test1.begin(), test1.end(), ::isdigit), test1.end());
std::cout << test1 << "nn";
// All in one alternative
std::copy_if(test2.begin(), test2.end(), std::ostream_iterator<char>(std::cout), [](const char c) { return 0 == std::isdigit(c); });
return 0;
}
如果有两个数字彼此相邻,则跳过第二个数字。发生这种情况是因为索引 i
不断上升,即使所有内容都发生了变化:
for (size_t i {}; i < digalpha.size(); i++)
if (isdigit(digalpha.at(i)))
digalpha.erase(i,1); //Here, i goes up anyway, skipping character after digit
要解决此问题,我们只需要在擦除数字后谴责i
:
for (size_t i {}; i < digalpha.size(); i++) {
if (isdigit(digalpha.at(i))) {
digalpha.erase(i,1);
i--;
}
}