2011-03-15 23 views
0

爲什麼不能在string.erase中調用string.find,如下所示:str.erase(str.find(a[1]),str.size())? 編輯:代碼添加你如何使用string.erase和string.find?

#include "stdafx.h" 
#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

// html tags 
string tags[5]={"<!--...-->","<!DOCTYPE>","<a>","<abbr>","<acronym>"}; 
// 

//check if string exists 
int boolStringExists(string a, string b) 
{ 
    if(a.find(b)>0) 
    { 
     return 1; 
    } 
    if(a.find(b)<=0) 
    { 
     return 0; 
    } 

} 
//erase tag from string a 
void eraseTags(string a,string b[]) 
{ 

    for(int i=0; i<5;i++) 
    { 
     int x=(boolStringExists(a,b[i])); 
     while (x>0) 
     { 
      a.erase(a.find(b[i]),b[i].size()); 
      x=(boolStringExists(a,b[i])); 
     } 
    } 
} 
int _tmain(int argc, _TCHAR* argv[]) 
{  
    fstream file; 
    file.open("h:\\a.htm"); 
    string k,m; 



    while(getline(file, k)) 
     m += k ; 


    eraseTags(m,tags); 


    return 0; 
} 

給出了這樣的消息:「此應用程序已請求運行時終止它在一個不尋常的way.Please聯繫人應用程序的支持團隊以獲取更多信息。」

+0

size_t pos = str.find(a[1]); if (pos != std::string::npos) str.erase(pos); //str.size() is not needed! 

現在,這不給錯誤?如果您有錯誤,請將其與相關代碼一起發佈。理想情況下,這是一個編譯,運行和再現錯誤的最小代碼示例。 –

回答

1

有什麼不妥調用(假設a[1]存在和str發現至少一次)

#include <iostream> 
#include <string> 
int main() 
{ 
     std::string str = "Hello, world!"; 
     std::string a = "wwwwww"; 
     str.erase(str.find(a[1]), str.size()); 
     std::cout << str << '\n'; 
} 

試運行:https://ideone.com/8wibR

編輯:您的完整的源代碼失敗,以檢查是否b[1]是實際上在str找到。如果a.find(b)大於零,則函數boolStringExists()返回1,並且在a中找不到b時返回的值std::string::npos大於零。

爲了解決這個問題,同時保持你的邏輯的其餘部分完好,該功能更改爲

//check if string exists 
bool boolStringExists(string a, string b) 
{ 
    return a.find(b) != string::npos; 
} 
+0

謝謝你的工作。 –

1

看來你要刪除str.find之後到來的一切(一[1])。在這種情況下,您可以省略第二個參數。

#include <iostream> 
#include <string> 

int main(int argc, char *argv[]) { 
     std::string str = "Hello, world!"; 
     std::string needle = "o,"; 
     str.erase(str.find(needle)); 
     std::cout << str << "\n"; 
} 

在這個例子中我用needle代替a[1],但原理是相同的。