码迷,mamicode.com
首页 > 其他好文 > 详细

How to find a specific string in a text file?

时间:2015-03-10 13:31:21      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

How to find a specific string in a text file?
how i did it: i store the whole contents of the .txt file in a single string, close the file, and then, split the string, based on searching a specific character: a | bar.

text file test.txt:
helloooooooooo|cool cool|another string|laaaaast one|
the bar "|" is needed to separate words/sentences.

and main.cpp:

 1 #include <iostream>
 2 #include <string>
 3 #include <sstream>
 4 #include <fstream>
 5 
 6  int main(){
 7     //load the text file and put it into a single string:
 8     std::ifstream in("test.txt");
 9     std::stringstream buffer;
10     buffer << in.rdbuf();
11     std::string test = buffer.str();
12     std::cout << test << std::endl << std::endl;
13 
14     //create variables that will act as "cursors". we‘ll take everything between them.
15     size_t pos1 = 0;
16     size_t pos2;
17 
18     //create the array to store the strings.
19     std::string str[4];
20 
21     for (int x=0; x<=3; x++){
22         pos2 = test.find("|", pos1); //search for the bar "|". pos2 will be where the bar was found.
23         str[x] = test.substr(pos1, (pos2-pos1)); //make a substring, wich is nothing more 
24                                               //than a copy of a fragment of the big string.
25         std::cout << str[x] << std::endl;
26         std::cout << "pos1:" << pos1 << ", pos2:" << pos2 << std::endl;
27         pos1 = pos2+1; // sets pos1 to the next character after pos2. 
28                          //so, it can start searching the next bar |.
29     }
30  }

 

EDIT: and the output:

helloooooooooo|cool cool|another string|laaaaast one|

helloooooooooo
pos1:0, pos2:14
cool cool
pos1:15, pos2:24
another string
pos1:25, pos2:39
laaaaast one
pos1:40, pos2:52

Process returned 0 (0x0)   execution time : 0.047 s
Press any key to continue.

 

 test.find("\\", pos3);  

To find a "\" should use "\\".

 

How to find a specific string in a text file?

标签:

原文地址:http://www.cnblogs.com/Tim-hy/p/4325597.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!