C++, Searching and returning value
For example, lets say I have this st开发者_JAVA百科ring:
"Name, Name2, <b>Name3</b>, Name4, <b>Name5</b>"
I am trying to get whatever value / name is inside the <b>
tags. So when I search the char, I get the following in an array:
Name3
Name5
Any ideas? Thanks
For this type of string searching / matching approach, just use boost regex.
Here's a basic version using only STL which assumes that the tags are not nested or otherwise misbehaving
#include <iostream>
#include <string>
#include <vector>
int main()
{
const std::string TAG_OPEN( "<b>" );
const std::string TAG_CLOSE( "</b>" );
const std::string s( "Name, Name2, <b>Name3</b>, Name4, <b>Name5</b>" );
typedef std::vector< std::string > StringArray;
StringArray tagContents;
std::string::size_type index = 0;
while( index != std::string::npos )
{
const std::string::size_type o = s.find( TAG_OPEN, index );
if ( o == std::string::npos )
{
break;
}
const std::string::size_type c = s.find( TAG_CLOSE, index );
if ( c == std::string::npos )
{
// mismatched tag, ignore?
break;
}
const std::string::size_type tagContentsStart = o + TAG_OPEN.size();
const std::string::size_type tagContentsFinish = c;
tagContents.push_back(
s.substr( tagContentsStart
, tagContentsFinish - tagContentsStart ) );
index = c + TAG_CLOSE.size();
}
for ( StringArray::const_iterator S = tagContents.begin();
S != tagContents.end();
++S )
{
std::cout << *S << std::endl;
}
return 0;
}
start = strstr(s, "<b>")+3;
stop = strstr(start, "</b>");
strncpy(result, start, stop-start);
Don't forget to add error checking.
subsequent matches, for the lazy ones:
s = stop+3;
execute the above code again.
[EDIT] To stop/error checking: check return code of strstr.
If you refuse to use std::string
and insist on using C-style string, you can always be adventurous and use strtok
. It has the feature of modifying your text strings.
Please read up on the side-effects of strtok
before using it.
I still strongly suggest making a std::string
with your chars, then using the std::string
for parsing. There are a lot more features with std::string
than with C-style strings.
精彩评论