|
|
|
String programs
This section contains example programs to demonstrate the use of strings.
A simple string example.
#include
main() { char str[80] ;
printf("Enter a string: ") ; gets(str) ; printf("%s" , str);
printf("\n"); }
The follow program requests the input of two strings, then demonstrates the four string functions with them.
#include #include
main() { char str1[80], str2[80]; int i;
printf("Enter the first string: "); getstr(str1); printf("Enter the second string: "); getstr(str2);
/* see how long the strings are */ printf("%s is %d chars long\n", str1, strlen(str1)); printf("%s is %d chars long\n", str2, strlen(str2));
/* compare the strings */ i= strcmp(str1, str2); if (!i) printf("The strings are equal.\n"); else if (i<0) printf ("%s is less than %s\n", str1,str2); else printf("%s is greater than %s\n", str1, str2);
/* concatenate str2 to end of str1 if there is enough room*/ if (strlen(str1)+ strlen(str2) < 80) { strcat(str1, str2); printf("%s\n", str1); }
/* copy str2 to str1 */ strcpy(str1, str1); printf("%s %s\n", str1, str2); }
|
| Author: Tejwant Singh Randhawa 15 Jun 2008 | Member Level: Silver Points : 2 |
nice program to explain the string operation. In c program string operation are performed by string function. strcmp() function is used to compare two strings. strlen() function is used to find the length of the string, strcat() function is used to concatenate two string & strcpy() function is used to copy the one string to another string.
|