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 *
* Description: This is code shows use of common string functions. *
\****************************************************************************/
#include
#include
#define SIZE 25
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 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 */
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);
}
The Sample Run
retriever[102] a.out
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
retriever[103]