String Finding Question

M

Mike Copeland

The C++ "find" functions seem more cumbersome than their C ancestors.
To me, string::find is more difficult to use than, say, strchr. For
example,

char *ptr = strchr("AEMT", 'A');
if(ptr != NULL) do_something_if_found;
else do_not_found;

Is there a simpler C++ way to code the following?

std::string valids = "AEMT";
size_t idx = valids.find('A');
if(idx != string::npos) do_something_if_found;
else do_not_found;
 
M

Marcel Müller

The C++ "find" functions seem more cumbersome than their C ancestors.
To me, string::find is more difficult to use than, say, strchr. For
example,

char *ptr = strchr("AEMT", 'A');
if(ptr != NULL) do_something_if_found;
else do_not_found;

Is there a simpler C++ way to code the following?

std::string valids = "AEMT";
size_t idx = valids.find('A');
if(idx != string::npos) do_something_if_found;
else do_not_found;

Where is the difference? Do you claim about the extra line for the
constant valids? You could eliminate it:
size_t idx = std::string("AEMT").find('A');

However, declaring valids as a static constant saves the allocations
needed for std::string constructor.


Marcel
 
M

Mike Copeland

Where is the difference? Do you claim about the extra line for the
constant valids? You could eliminate it:
size_t idx = std::string("AEMT").find('A');

However, declaring valids as a static constant saves the allocations
needed for std::string constructor.
Yes, I do find the extra line annoying, but your reply is the sort of
thing I was seeking: a shorthand way to scan a constant without all the
extraneous declaration, etc. Thank you. 8<}}
 
J

Jorgen Grahn

The C++ "find" functions seem more cumbersome than their C ancestors.
To me, string::find is more difficult to use than, say, strchr. For
example,

char *ptr = strchr("AEMT", 'A');
if(ptr != NULL) do_something_if_found;
else do_not_found;

Is there a simpler C++ way to code the following?

std::string valids = "AEMT";
size_t idx = valids.find('A');
if(idx != string::npos) do_something_if_found;
else do_not_found;

I prefer using std::find, since I'm more familiar with iterators than
that funny string-specific stuff:

std::string valids = "AEMT";
if(std::find(valids.begin(), valids.end(), 'A') != valids.end()) {
do_something_if_found;
}
else {
do_not_found;
}

If I do this a lot in a source file, I'll probably write a

bool contains(const string&, char);

helper function.

/Jorgen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top