Reputation: 45
I have a file that I have read and I want to read each individual line as if it were a string and compare each line to find certain keywords and if I find those certain keywords, take everything within those keywords and make a new string out of it. It is possible to have more than one line with the same keywords, so I would like to create separate strings...
I have some ugly looking code right now that it would be embarrassing to put here, can someone point me in the right direction of how to do this...
I can put my code here if you like, but I'll have to explain it a lot.
AGU UAC AUU GCG CGA UGG GCC UCG AGA CCC GGG UUU AAA GUA GGU GA
GUU ACA UUG CGC GAU GGG CCU CGA GAC CCG GGU UUA AAG UAG GUG A
UUA CAU UGC GCG M GGC CUC GAG ACC CGG GUU UAA AGU AGG UGA
UGG M AAA UUU GGG CCC AGA GCU CCG GGU AGC GCG UUA CAU UGA
This would be part of my text file. I want to find 'M' and then find instances of: 1) UAA, 2) UAG, or 3) UGA. And make each one a separate string so that I can compare their lengths. I tried using the assignment operator, but it would print out the same string every time.
ED. I guess what I would like to do is just find any instance of 'M', when I do, I would like to make that whole line into a string so I can compare the strings.
ifstream code_File ("example.txt"); // open text file.
if (code_File.is_open()) {
while (code_File.good()) {
getline(code_File,line); //get the contents of file
cout << line << endl; // output contents of file on screen.
found = line.find_first_of('M', 0); // Finding start code
if (found != string::npos) {
code_Assign.assign(line, int(found), 100); //assign the line to code_Assign and print out string from where I found the start code 'M'.
cout << endl << "code_Assign: " << code_Assign << endl << endl;
Upvotes: 0
Views: 532
Reputation: 153919
It's not at all clear to me what you are trying to do, however:
To read a line and put it in a single string: use std::getline
.
To find a fixed string in another string, use std::search
; for more
complicated patterns, use boost::regex
(or std::regex
if you have a
C++11 compiler). std::search
will return an iterator, and two
iterators can be used to construct a new string. The regex
solutions
can “capture”, so you have access to the intervening string
directly (or not; a lot depends on how complicated the pattern is, and
the regex
solution doesn't work when the string you want to capture is
in a repeated pattern). Without more information, however, it is
difficult to say more.
Try specifying your problem precisely; I think you'll find that that helps in finding a solution.
Upvotes: 0
Reputation: 1
That seems a good task for grep
or sed
or awk
standard Posix utilities.
If you want it (faster) inside a program, consider using standard parsing techiques e.g. with ANTLR
Upvotes: 1