我必须处理一大块文本,从头到尾对它进行线性分析。我想知道哪种方法更好:使用char*或std::string。使用char*时,我可以将指针更改为字符串中更远的位置,例如。
//EDIT later: mallocing some space for text
char str[] = "text to analyse";
char * orig = str;
//process
str += processed_chars; //quite fast
//process again
// later: free(orig);但是使用字符串,我可能不得不使用std:: string ::erase --但是它会创建一个副本,或者移动字节或者其他东西(我不知道实际的实现)
string str = "text to analyse";
//process
str = str.erase(0,processed_chars);或者有没有办法改变std::string的隐藏指针?
编辑:由于Sylvain Defresne在这里请求更多代码:
class tag {
public:
tag(char ** pch) {
*pch = strstr(*pch,"<");
if(pch == NULL) return;
char *orig = *pch+1;
*pch = strstr(*pch,">");
if(pch == NULL) return;
*pch+=sizeof(char); //moving behind the >
//process inner tag data
if(*(*pch-2)!='/'){// not selfclose
while (!(**pch == '<' && *(*pch+1) == '/')){ //sarch for closing tag
tag* kid = new tag(pch);
sublings.push_back(*kid);
}
*pch = strstr(*pch,">");
if(pch == NULL) return;
*pch+=sizeof(char); //moving behind the >
//add check if the clothing tag is matching
}
}
}我将其用于类似于xml的递归表示法解析
char str[] ="<father><kid /></fatherr>";
char * pch = str;
tag *root = new tag(&pch);这段代码难看得要死,我只是从低级指针算法和其他东西开始,到目前为止还在使用可视化组件,所以不要太难判断
发布于 2011-03-16 23:20:16
对于std::string,您可能会使用std::string::iterator。你的代码应该是:
std::string str = "text to analyse";
std::string::iterator iter = str.begin();
// process
iter += processed_chars; 发布于 2011-03-16 23:20:35
你可以用char*做的任何事情,你都可以用std::string::iterator来做。
发布于 2011-03-16 23:21:56
您可以使用std::string::iterator (查看here)。
在这样的任务中,std::string不是必需的(但像std::string这样的类在其他情况下非常有用)。
https://stackoverflow.com/questions/5327408
复制相似问题