好吧,我必须处理大量文本,从头到尾对其进行线性分析。我想知道更好的方法是什么:使用 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);
这段代码丑得要死,我只是从低级指针算术和东西开始,直到现在都使用可视化组件所以不要判断得太难
最佳答案
对于 std::string
,您可能会使用 std::string::iterator
。您的代码将是:
std::string str = "text to analyse";
std::string::iterator iter = str.begin();
// process
iter += processed_chars;
关于c++ - std string vs char performance,从一开始就删除部分的最佳技术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5327408/