Archived

This topic is now archived and is closed to further replies.

STL's version of strncmp

This topic is 5127 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

How would you do a strncmp with the stl''s string? I''ve tried findfirstof, and find, and neither really seemed to work just right. For example, how would I do the following:

char *acharstring = "PARENT-25";

if(strncmp(acharstring, "PARENT", 6) == 0)
{
}

 

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
You could try:

std::string a = new std::string("PARENT-25";
if(a.substr(0, 6) == "PARENT" {
// do something
}

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Maybe this will eliminate the weird smilies:

std::string a = new std::string("PARENT-25" ) ;
if(a.substr(0, 6) == "PARENT" ) {
// do something
}

Share this post


Link to post
Share on other sites
if you want to use stl perhaps this is what you''re after:



#include <algorithm>

int main()
{
std::string word = "parent-25";
std::string subword = "parent";
std::string::const_iterator i = search(word.begin(),word.end(),subword.begin(),subword.end());

...
return 0;
}


now upon success ''i'' will return an iterator that will be != word.end(). Failure will return word.end() assigned to ''i''.

That is just the basic schematic of how one can use it.




|PicRepository|PicIndex|
IM: CScoder@aol.com/ahmed7500@hotmail.com
The Gatekeeper of quotes passé:
"How Appropriate. You fight like a cow" --Sneftel

Share this post


Link to post
Share on other sites
I like the above solution the best, but I thought I''d point out that std::string has a cstr() method.

You can use it to have the std::string return a char * for you, which of course can be used to in strncmp.

Cheers
Chris

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster
Maybe this will eliminate the weird smilies:

std::string a = new std::string("PARENT-25" ) ;
if(a.substr(0, 6) == "PARENT" ) {
// do something
}



You must be a Java programmer :-) You need to declare ''a'' as a pointer if you are going to ''new'' it.

Share this post


Link to post
Share on other sites