find in string
I need to find position of certain character in string, so i made a function but it doesn't do what i thought it would.
Consider this string:
|
std::string line = "<foo> <foo> <foo> <foo> <foo>"
|
I need to find position of a third '>' character so i can get:
|
std::string other = "<foo> <foo> <foo>";
|
This is my function that fails:
1 2 3 4 5 6 7 8 9 10
|
std::size_t find_third(const std::string& line)
{
std::size_t pos = 0u;
for(std::size_t i = 0; i < 3u; ++i)
{
std::string tmp = line.substr(pos);
pos = tmp.find_first_of('>');
}
return pos;
}
|
Thank you for your time.
I have not understood what id the relation berween the third symbol '>' in the original string and
std::string other = "<foo> <foo> <foo>";
How is this string formed?
I don't know how better to explain, my english sucks.
I have a string with 5 blocks of "stuff":
|
std::string line = "<blah128> <34foo> <b2ar1> <28rab11> <6a1rb>";
|
and i need to extract first 3 from that so that i have:
|
std::string other = "<blah128> <34foo> <b2ar1>";
|
Thank you for your time.
How about something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
#include <iostream>
#include <string>
using namespace std;
void findSubString(string &line, string &subString);
int main()
{
string line = "<foo> <foo> <foo> <foo> <foo>";
string subString;
findSubString(line, subString);
return 0;
}
void findSubString(string &line, string &subString)
{
int numOfClosingBrackets = 0;
for(size_t i=0; i<line.size(); i++)
{
subString.push_back(line[i]);
if(line[i]=='>')
{
numOfClosingBrackets++;
if(numOfClosingBrackets==3)
{
break;
}
}
}
}
|
Last edited on
1 2 3 4 5 6 7 8 9 10 11 12
|
std::string::size_type find_third(const std::string& line)
{
std::string::size_type pos = 0;
for ( int i = 0; i < 3 && pos != std::string::npos; ++i )
{
pos = line.find( '>', pos );
if ( pos != std::string::npos ) pos++;
}
return pos;
}
|
EDIT: I have uodated the code.
Last edited on
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
#include <iostream>
#include <string>
std::size_t find_nth(const std::string& line, char ch, unsigned nth )
{
std::size_t pos = line.find(ch) ;
unsigned nFound = 1 ;
while ( nFound < nth && pos != std::string::npos )
{
if ( pos+1 < line.length() )
{
pos = line.find('>', pos+1) ;
++nFound ;
}
else
pos = std::string::npos ;
}
return pos ;
}
int main()
{
std::string line = "<foo> <foo> <foo> <foo> <foo>" ;
std::size_t pos = find_nth(line, '>', 3) ;
if ( pos != std::string::npos )
std::cout << line.substr(0, pos+1) << '\n' ;
}
|
Thank you everybody.
Topic archived. No new replies allowed.