2012-10-18 54 views
0

我想在std :: string中找到3次或更多次出现以替换。替换3次或更多次出现的字符串

例如:

std::string foo = "This is a\n\n\n test"; 
std::string bar = "This is a\n\n\n\n test"; 
std::string baz = "This is a\n\n\n\n\n test"; 
std::string boo = "This is a\n\n\n\n\n\n test"; 
// ... etc. 

应该所有被转换成:

std::string expectedResult = "This is a\n\n test"; 

香草STL,将不胜感激(没有正则表达式库或增压)如果可能的话。

+2

你试过了什么? –

+0

@ÖöTiib:我可以通过计算连续出现的次数来获得开始和结束pos,但我希望能有更多的STL方法 –

回答

2

这应该找到连续\ n和替换它们:

size_type i = foo.find("\n\n\n"); 
if (i != string::npos) { 
    size_type j = foo.find_first_not_of('\n', i); 
    foo.replace(i, j - i, "\n\n"); 
} 
+0

我不知道find_first_not_of ...应该有帮助 –

+0

Find_first_of works通过查找*字符*而不是子字符串...我会看看如果我可以适应使用查找和更新,如果我得到一个工作的解决方案。 –

+0

@JamesFassett你说的对,使用'find()'应该修复它。 –

0

写一个函数来处理每一个你感兴趣字符串修改:

时间阅读每个字符串一个字符。跟踪2个字符变量:a和b。对于每个字符c你读,做:

if (a != b) { 
    a = b; 
    b = c; 
} else if (a == b) { 
    if (a == c) { 
     // Put code here to remove c from your string at this index 
    } 
} 

我不是100%肯定,如果你可以使用的东西,从STL直接来完成你的要求,但你可以看到这种逻辑并不多码实行。

0

您可以使用查找和替换。 (这将取代“\ n \ n \ n ...” - >“\ n \ n”)。您可以通过位置串::发现,这样你就不必再次搜索字符串的开头(优化)

int pos = 0; 
    while ((pos = s.find ("\n\n\n", pos)) != s.npos) 
    s.replace (pos, 3, "\n\n", 2); 

,这将取代“\ n \ n \ n \ n ..” - >“\ n”

int pos = 0; 
    while ((pos = s.find ("\n\n", pos)) != s.npos) 
    s.replace (pos, 2, "\n", 1); 
相关问题