Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

manipulating a string 1

Status
Not open for further replies.

jimberger

Programmer
Jul 5, 2001
222
GB
hi all,

I have a char * which is delimitered by commas e.g

char * string = "cn=text1,text2,text3";

I want to parse this string to return just text1

A sed command would be something like

$string =~ /^cn=(.*[0-9]),.*$/;
$tex1 = $1;

but i have no idea how to do something similar in C. Any ideas? Thanks for your time

jim

 
#include <stdio.h>
#include <string.h>

#define SEARCH &quot;text1&quot;
#define SPLIT &quot;=,&quot;

int main( void )
{
char *sStr = &quot;cn=text1,text2,text3&quot;;
char *pTemp;
int iFind;

pTemp = strtok( sStr,SPLIT );
iFind = 0;

do {

pTemp = strtok( NULL, SPLIT );

if ( pTemp )
if ( !strcmp( pTemp,SEARCH ) )
{
iFind = 1;
break;
}

} while ( pTemp );


if ( iFind )
printf( &quot;%s was FOUND in the string.\n&quot;,pTemp );
else
printf( &quot;%s string was NOT FOUND.\n&quot;,
SEARCH );

return 0;

} Mike L.G.
mlg400@blazemail.com
 
Bug in first source, sorry.
The do/while loop will split the string (tokenize). The deliminators are #defined by SEARCH.
So &quot;cn=text1,text2,text3&quot; will be split into &quot;cn&quot; &quot;text1&quot; &quot;text2&quot; &quot;text3&quot;.

#include <stdio.h>
#include <string.h>

#define SEARCH &quot;text1&quot;
#define SPLIT &quot;=,&quot;

int main( void )
{
char *sStr = &quot;cn=text1,text2,text3&quot;;
char *pTemp;
int iFind;

pTemp = strtok( sStr,SPLIT );
iFind = 0;

do {

if ( pTemp )
if ( !strcmp( pTemp,SEARCH ) )
{
iFind = 1;
break;
}

pTemp = strtok( NULL, SPLIT );

} while ( pTemp );


if ( iFind )
printf( &quot;%s was FOUND in the string.\n&quot;,pTemp );
else
printf( &quot;%s string was NOT FOUND.\n&quot;,
SEARCH );

return 0;

}





Mike L.G.
mlg400@blazemail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top