STL's version of strncmp

Started by
7 comments, last by JoeyBlow2 20 years, 4 months ago
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)
{
}

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

EDIT: Someone was faster...

[edited by - bakery2k1 on November 28, 2003 12:11:40 PM]
Maybe this will eliminate the weird smilies:
std::string a = new std::string("PARENT-25" ) ;if(a.substr(0, 6) == "PARENT" ) {    // do something}  
Thanks. =) I''ll try that substr.
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
Well, R2D22U2..
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
CheersChris
What the fuck?

The direct analogue is basic_string::compare(). What the hell are you creating substrings for? Deliberate inefficiency?

char a[99999],*p=a;int main(int c,char**V){char*v=c>0?1[V]:(char*)V;if(c>=0)for(;*v&&93!=*v;){62==*v&&++p||60==*v&&--p||43==*v&&++*p||45==*v&&--*p||44==*v&&(*p=getchar())||46==*v&&putchar(*p)||91==*v&&(*p&&main(0,(char**)(--v+2))||(v=(char*)main(-1,(char**)++v)-1));++v;}else for(c=1;c;c+=(91==*v)-(93==*v),++v);return(int)v;}  /*** drpizza@battleaxe.net ***/
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.

This topic is closed to new replies.

Advertisement