2012-02-04 79 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()