简体   繁体   English

搜索LPSTR字符串

[英]Searching LPSTR string

I want to find some words after i get the whole file to char*. 在将整个文件保存到char *之后,我想找到一些单词。 I know how to do it using the string class functions but i don't want to copy the data again to a string variable. 我知道如何使用字符串类函数来执行此操作,但是我不想再次将数据复制到字符串变量中。 is there any similar functions available to use for char* strings or should i still use string class? 是否有任何类似的功能可用于char *字符串,或者我是否仍应使用字符串类?

http://www.cplusplus.com/reference/clibrary/cstring/strstr/ http://www.cplusplus.com/reference/clibrary/cstring/strstr/

The string manipulation functions for basic strings are situated in the cstring / string.h header: http://www.cplusplus.com/reference/clibrary/cstring/ 基本字符串的字符串操作函数位于cstring / string.h标头中: http ://www.cplusplus.com/reference/clibrary/cstring/

You can search using strstr (for one example). 您可以使用strstr搜索(例如)。 If the data is large enough that the copying time is significant, it would probably be worth using something like a Boyer-Moore-Horspool search. 如果数据足够大以至于需要大量的复制时间,则可能值得使用类似Boyer-Moore-Horspool的搜索方式。

Why don't you just load the file into a string in the first place since you know how to use it? 您为什么不首先将文件加载到字符串中,因为您知道如何使用它?

#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <algorithm>

int main( int argc, char* argv[] ){
std::ifstream ifsFile( <file_name> );
ifsFile.unsetf( std::ios_base::skipws ); // make sure we're not skipping whitespaces

std::istream_iterator< char > begin( ifsFile ), end;
std::string strFile( begin, end ); // load the file into the string

// now print the file/search for words/whatever
std::copy( strFile.begin(), strFile.end(), std::ostream_iterator< char >( std::cout, "" ) );

return 0;
}

You will likely need to use more than strstr() because you'll probably be interested in word boundaries (I;m guessing that you'll need to find matches that are bounded by whitespace or the start/end of the line). 您可能需要使用比strstr()更多的内容,因为您可能会对单词边界感兴趣(我想您可能需要查找以空格或行的开头/结尾为边界的匹配项)。

Various standard library functions that might be of interest: 可能感兴趣的各种标准库函数:

strstr()
strtok() (or it's non-standard but sill useful cousin strtok_r())
strspn()
strpbrk()
strcspn()
strchr()

But, string parsing is a real pain in straight C (in my experience), you may want to look for an existing parsing library (or regex library) that might help mitigate the pain. 但是,字符串解析是直接C语言的真正痛苦(以我的经验),您可能想寻找一个现有的解析库(或regex库)来帮助减轻痛苦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM