我正在尝试使用Erase()函数从字符串中擦除特定字符,但是它不起作用。
该问题表明您必须删除“ AB”或“ BB”子字符串。当从字符串中删除子字符串时,字符串的其余部分将被连接起来,过程将继续...
代码如下:
#include <bits/stdc++.h>
#define ios ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define int long long int
using namespace std;
int32_t main()
{
ios;
int t;
cin>>t;
while(t--)
{
string s;
cin>>s;
int i;
for(i=0;i<s.length();i++)
{
if(s[i]=='A'&&s[i+1]=='B')
{
s.erase(i,i+1);
cout<<s<<"\n";
i=-1; // I want to start from begining therefore initializing i=-1 after i++ it becomes i=0;
}
else if(s[i]=='B'&&s[i+1]=='B')
{
s.erase(i,i+1);
cout<<s<<"\n";
i=-1;
}
}
//cout<<s.length()<<"\n";
}
return 0;
}
输入:
1
AABBBABBBB
输出为:
ABBABBBB
BBABBBB
BABBBB
BBBB
BBB
BB
B
但是输出应该是:
ABBABBBB
BABBBB
BBBB
BB
我做错什么了吗?
答案 0 :(得分:1)
您可以将两个s.erase(i, i + 1);
语句更改为s.erase(i, 2);
。
1
AABBBABBBB
ABBABBBB
BABBBB
BBBB
BB
您可以使用C ++ STL。
#include <vector>
#include <iostream>
#include <string>
int main() {
int t{0};
std::cin >> t;
while (t--) {
std::string s{};
std::cin >> s;
for (auto i = 0; i < s.length() && i + 1 < s.length(); i++) {
if (s[i] == 'A' && s[i + 1] == 'B') {
s.erase(i, 2);
std::cout << s << std::endl;
i = -1;
} else if (s[i] == 'B' && s[i + 1] == 'B') {
s.erase(i, 2);
std::cout << s << std::endl;
i = -1;
}
}
}
return EXIT_SUCCESS;
}
答案 1 :(得分:1)
我做错什么了吗?
是的,几乎所有内容。
#include <iostream>
#include <string>
#include <regex>
int main()
{
std::regex re("AB|BB");
int t;
std::cin >> t;
while(t--)
{
std::string s;
std::cin >> s;
std::string prev;
// do one replacement at a time, until there are no changes
do
{
std::cout << s << '\n';
prev = s;
s = std::regex_replace(s, re, "", std::regex_constants::format_first_only);
} while (s != prev);
}
return 0;
}
答案 2 :(得分:-1)
这只是气泡排序的简单变体。
#include <iostream>
#include <string>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while(t > 0 && t--)
{
string s;
cin >> s;
for(size_t i = 0; i < s.length(); i++) {
for(size_t j = 0; j < s.length() - 1; j++) {
if((s[j]=='A' || s[j] == 'B') && s[j+1]=='B')
{
s.erase(j,2);
cout<<s<<"\n";
break;
}
}
}
}
return 0;
}