Reputation: 2335
I have a number of strings which are of the format #include "filename.h" I need to pullout the filename.h part from all these strings. For Instance, #include "apple.h" #include "mango.h" #include "Strawberry.h".
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;
Output: Strawberry.h"
How do I get rid of the " in the end and just get apple.h or Strawberry.h?
Upvotes: 3
Views: 282
Reputation: 7136
Maybe something like,
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
EDIT: fixed bug, was adding last quotation mark
Upvotes: 4
Reputation: 26586
I think you are on the right track, but the only problem is that the second argument of your substr
call is not quite right. substr
takes as its arguments the starting offset and the length of the substring you want. In your case, you want everything from the 10th and up to the second to last character (the last character is "
). So you want a string that starts at 10 and ends at line.size()-(10+1)
(you have to subtract 10 because you are skipping them at first and then one more to not include the trailing "
).
Try:
cout<<x.substr(10,line.size()-11)<<endl;
Upvotes: 2
Reputation: 121639
"substr(10, ...)" arguably isn't the way to do it :)
Personally, I'd recommend considering a "regex" to take everything between the two quote marks, regardless of what the start or end position of either quote mark is:
http://softwareramblings.com/2008/07/regular-expressions-in-c.html
Upvotes: 0