2012-02-04 122 views
3

我有一些格式爲#include「filename.h」的字符串,我需要從所有這些字符串中提取filename.h部分。例如,#include「apple.h」#include「mango.h」#include「Strawberry.h」。在C++中修剪字符串

 getline(Myfile,str1); //str1 now contains a line from a text file i.e #include "Strawberry.h" 
    std::cout <<"\t\t"<<str1.substr(10,(line.length())) <<std::endl; 

輸出: Strawberry.h 「

如何獲得擺脫」 到底和剛剛獲得apple.h或Strawberry.h?

回答

2

我認爲你是在正確的軌道上,但唯一的問題是,您的通話substr的第二個參數是不完全正確。 substr以其參數爲起始偏移量和所需子字符串的長度。在你的情況下,你需要從第10個到第二個到最後一個字符(最後一個字符是")。所以你需要一個字符串,從10開始到line.size()-(10+1)(你必須減去10,因爲你首先跳過它們,然後再一次不包含尾隨的")。

嘗試:

cout<<x.substr(10,line.size()-11)<<endl; 
+0

謝謝你這個工作MAK! – 2012-02-04 05:31:17

+0

@Deepak B - 我完全不同意。硬編碼的值是「壞」。user814628的建議可能需要三行 - 但它是正確的方法你*真的*想「找到引號之間的字符串」NOT「位置10和len-11之間的字符串」恕我直言...... – paulsm4 2012-02-04 18:16:47

+0

@ paulsm4:我的假設是該行的格式是固定的並且在它之前只有一組帶引號的字符串「#include」。嘗試任意字符串需要比僅僅查找開始和結束引號更復雜的內容(可能有多於一組引號,引號可能嵌套等等。) – MAK 2012-02-04 22:46:47

4

也許是這樣,

string::size_type beg = str1.find_first_of("\""); //find first quotation mark 
string::size_type end = str1.find_first_of("\"", beg + 1); //find next quotation mark 
string result = str1.substr(beg + 1 , end - (beg + 1)); //return the portion in between 

編輯:修正,是加入洛杉磯ST引號

+1

+1的方法!這很接近,但'size_t'不是'string'的成員,並且你正在包括關閉'''。請參閱http://ideone.com/8Lrwp以獲得修復 – Johnsyweb 2012-02-04 05:13:16

+0

您的權利,忘記添加+1我想在string :: size_type。 – dchhetri 2012-02-04 05:22:19

0

嘗試line.length() - 1,而不是line.length()