String Functions
The most commonly used :
- Find the length of a string: strlen
- Copy one string into another: strcpy
- Compare two strings: strcmp
- To see if they are equal, (returns 0 if they're equal)
since if(str1 == str2) just compares 2 addresses,
which are never equal, but does not cause a syntax error.
- Indicates lexicological order, appropriate for sorting
returns negative if first string is less than the second,
or positive if first string is greater than the second.
- Concatenate two strings: strcat
The Program
/**********************************************************
* Filename: stringfuncs.c
* Author: Sue Bogar
* Date written: 11/28/97
* Modified: 09/26/05
* Section: 101
* EMail: bogar@cs.umbc.edu
*
* Description:
* This code shows use of the most common string functions.
**********************************************************/
#include <stdio.h>
#include <string.h>
#define SIZE 25
int main ( )
{
int length, comparison;
char str1[SIZE] = "oranges";
char str2[SIZE] = "apples";
char str3[SIZE] = " and ";
char str4[SIZE];
/* Example using strlen */
length = strlen (str1);
printf ("The length of %s is %d\n",
str1, length);
/* strcpy copies second string into the first */
strcpy(str4, str1);
printf ("Just executed strcpy: str4 = %s & str1 = %s\n",
str4, str1);
/* compare apples and oranges */
/* strcmp can be used to check for equality or*/
/* for order*/
comparison = strcmp(str1, str2);
if (comparison < 0)
{
printf("%s is less than %s\n", str1, str2);
}
else if (comparison > 0)
{
printf("%s is greater than %s\n", str1, str2);
}
else
{
printf("%s and %s are equal\n", str1, str2);
}
/* strcat appends second string to the end of the*/
/* first one */
strcat(str2, str3);
printf("After the first concatenation:\n");
printf("str2 is: %s\n", str2);
strcat(str2, str1);
printf("After the second concatenation:\n");
printf("str2 is: %s\n", str2);
return 0;
}
The Sample Run
The length of oranges is 7
Just executed strcpy: str4 = oranges & str1 = oranges
oranges is greater than apples
After the first concatenation:
str2 is: apples and
After the second concatenation:
str2 is: apples and oranges
Last Modified -