在所需的代码中,我必须输入一个字符串,并在删除该字符串中的所有给定单词后输出该字符串。示例:假设我希望从字符串中删除WUB。
Input1:WUBWUBABCWUB
Output1:ABC
Input2:WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB
Output2:WE ARE THE CHAMPIONS MY FRIEND
这是我的代码:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string in;
cin>>in; //input
int n=in.length();
int pos =in.find("WUB");
for(;pos!=-1;){
pos =in.find("WUB");
if(pos!=-1){ //manipulating string by erasing and inserting spaces between words
in.insert(pos+3," ");
in.erase(pos,pos+3);
}
}
if(in[0]==' ')
in.erase(in.begin());
if(in[n-1]==' ') //removing extra spaces
in.erase(in.end());
cout<<in;
}它适用于输入1,但对于输入2则输出错误。Output2:WEETHEONSND
这里怎么了?
发布于 2019-12-05 12:51:41
您使用的string::erase的重载是
basic_string& erase( size_type index = 0, size_type count = npos );您将pos+3作为计数传递,而不是只传递3。
发布于 2019-12-05 13:28:28
与函数插入和擦除的两个顺序调用不同,您只能使用函数替换的一个调用。
此外,这一成员函数的调用
in.erase(pos,pos+3);第二个参数应指定需要删除的字符数。
此外,似乎你需要删除所有的领导和尾随空白,而不是只有一个空白从双方。
if(in[0]==' ')
in.erase(in.begin());
if(in[n-1]==' ') //removing extra spaces
in.erase(in.end());该程序可以如下所示
#include <iostream>
#include <string>
#include <limits>
int main()
{
while ( true )
{
std::cout << "Enter the source string (Enter - exit): ";
std::string s;
if ( not std::getline( std::cin, s ) or s.empty() ) break;
std::cout << "Enter the substring to remove: ";
std::string t;
std::cin >> t;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
if ( not t.empty() )
{
for ( auto pos = s.find( t );
pos != std::string::npos;
pos = s.find( t, pos ) )
{
s.replace( pos, t.size(), 1, ' ' );
++pos;
}
}
s.erase( 0, s.find_first_not_of( " \t " ) );
auto pos = s.find_last_not_of( " \t " );
if ( pos != std::string::npos ) s.erase( ++pos );
std::cout << "The source string: \"" << s << "\"\n";
}
return 0;
}它的输出可能看起来像
Enter the source string (Enter - exit): WUBWUBABCWUB
Enter the substring to remove: WUB
The source string: "ABC"
Enter the source string (Enter - exit): WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB
Enter the substring to remove: WUB
The source string: "WE ARE THE CHAMPIONS MY FRIEND"
Enter the source string (Enter - exit): 发布于 2019-12-05 13:49:23
通过使用Regex查找不需要的单词,然后用空格替换它们,您可以创建更高效、更简洁的代码。当然,您必须使用unique()来删除双空格。
码
#include <iostream>
#include <regex>
bool BothAreSpaces(char lhs, char rhs)
{
return (lhs == rhs) && (lhs == ' ');
}
int main()
{
string s("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB"); //Input string
regex e("(WUB)"); // Regex syntax to filtr unwanted string
string result; //Filtered string
regex_replace(std::back_inserter(result), s.begin(), s.end(), e, " "); //Replace unwanted word with space
string::iterator new_end = unique(result.begin(), result.end(), BothAreSpaces); //Find double spaces
result.erase(new_end, result.end()); //Remove double spaces
cout << result << endl;
}输出
WE ARE THE CHAMPIONS MY FRIENDhttps://stackoverflow.com/questions/59195276
复制相似问题