[英]Searching LPSTR string
在將整個文件保存到char *之后,我想找到一些單詞。 我知道如何使用字符串類函數來執行此操作,但是我不想再次將數據復制到字符串變量中。 是否有任何類似的功能可用於char *字符串,或者我是否仍應使用字符串類?
http://www.cplusplus.com/reference/clibrary/cstring/strstr/
基本字符串的字符串操作函數位於cstring / string.h標頭中: http ://www.cplusplus.com/reference/clibrary/cstring/
您可以使用strstr
搜索(例如)。 如果數據足夠大以至於需要大量的復制時間,則可能值得使用類似Boyer-Moore-Horspool的搜索方式。
您為什么不首先將文件加載到字符串中,因為您知道如何使用它?
#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;
}
您可能需要使用比strstr()
更多的內容,因為您可能會對單詞邊界感興趣(我想您可能需要查找以空格或行的開頭/結尾為邊界的匹配項)。
可能感興趣的各種標准庫函數:
strstr()
strtok() (or it's non-standard but sill useful cousin strtok_r())
strspn()
strpbrk()
strcspn()
strchr()
但是,字符串解析是直接C語言的真正痛苦(以我的經驗),您可能想尋找一個現有的解析庫(或regex庫)來幫助減輕痛苦。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.