strstr
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="This is a simple string";
char * pch;
pch = strstr (str,"simple");
printf("%s\n",pch);
printf("%p\n",str);
printf("%p\n",pch);
strncpy (pch,"sample",4);
puts (str);
return 0;
}
strchr
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "This is a sample string";
char * pch;
printf ("Looking for the 's' character in \"%s\"...\n",str);
pch=strchr(str,'s');
while (pch!=NULL)
{
printf ("found at %d\n",pch-str+1);
pch=strchr(pch+1,'s');
}
return 0;
}
strcmp
#include <stdio.h>
#include <string.h>
int main ()
{
char key[] = "apple";
char buffer[80];
do {
printf ("Guess my favorite fruit? ");
fflush (stdout);
scanf ("ys",buffer);
} while (strcmp (key,buffer) != 0);
puts ("Correct answer!");
return 0;
}
strcpy
/* strcpy example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[]="Sample string";
char str2[40];
char str3[40];
strcpy (str2,str1);
strcpy (str3,"copy successful");
printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
return 0;
}
strlen
#include <stdio.h>
#include <string.h>
int main ()
{
char szInput[256];
printf ("Enter a sentence: ");
gets (szInput);
printf ("The sentence entered is %u characters long.\n",(unsigned)strlen(szInput));
printf("%d\n",sizeof(szInput));
return 0;
}
memcpy
#include <stdio.h>
#include <string.h>
struct {
char name[40];
int age;
} person, person_copy;
int main ()
{
char myname[] = "Pierre de Fermat";
/* using memcpy to copy string: */
memcpy ( person.name, myname, strlen(myname)+1 );
person.age = 46;
/* using memcpy to copy structure: */
memcpy ( &person_copy, &person, sizeof(person) );
printf ("person_copy: %s, %d \n", person_copy.name, person_copy.age );
return 0;
}
memset
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "almost every programmer should know memset!";
memset (str,'-',6);
puts (str);
return 0;
}
strtol
#include <stdio.h> /* printf */
#include <stdlib.h> /* strtol */
int main ()
{
char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff";
char * pEnd;
long int li1, li2, li3, li4;
li1 = strtol (szNumbers,&pEnd,10);
printf("%s\n", pEnd);
li2 = strtol (pEnd,&pEnd,10);
printf("%s\n", pEnd);
li3 = strtol (pEnd,&pEnd,2);
printf("%s\n", pEnd);
li4 = strtol (pEnd,NULL,0);
printf("%s\n", pEnd);
printf ("The decimal equivalents are: %ld, %ld, %ld and %ld.\n", li1, li2, li3, li4);
return 0;
}
##atol Convert string to long integer
#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atol */
int main ()
{
long int li;
char buffer[256];
printf ("Enter a long number: ");
fgets (buffer, 256, stdin);
li = atol(buffer);
printf ("The value entered is %ld. Its double is %ld.\n",li,li*2);
return 0;
}