Below are some main string.h functions, click on anyone and go directly to that program.
strlen(), strcat(), strcpy(), strcmp()
Program:
1) strlen(): used to find length of string
#include <stdio.h>
#include <string.h>
void main()
{
int l;
char s[20];
printf("Enter String: ");
gets(s);
l=strlen(s); /* length of string will be stored in l */
printf("length of string is: %d",l);
getch();
}
Output:
Enter String: SlashMyCode.com
length of string is: 15
2) strcat(): used to join two strings.
#include <stdio.h>
#include <string.h>
void main()
{
int l;
char s1[40],s2[40];
printf("Enter String 1: ");
gets(s1);
printf("Enter String 2: ");
gets(s2);
strcat(s1,s2); /* join two strings i.e s1, s2 and new string is stored in s1 */
printf("Concatenated string is: ");
puts(s1);
getch();
}
Output:
Enter String 1: Get C Programs from:
Enter String 2: SlashMyCode.com
Concatenated string is: Get C Programs from: SlashMyCode.com
3) strcpy(): used to copy 2nd string over 1st
#include <stdio.h>
#include <string.h>
void main()
{
char s1[40],s2[40];
printf("Enter String 1: ");
gets(s1);
printf("Enter String 2: ");
gets(s2);
strcpy(s1,s2); /* overwrites 2nd strings over 1st and store it in s1 */
printf("1st string is: ");
puts(s1);
getch();
}
Output:
Enter String 1: Hiii
Enter String 2: Hello!
1st string is: Hello!
4) strcmp(): used to compare two strings according to ascii values of characters in string
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20], s2[20];
int result;
printf("Enter String 1: ");
gets(s1);
printf("Enter String 2: ");
gets(s2);
result = strcmp(s1,s2); /* comparing strings s1 and s2 */
printf("Result = %d\n",result);
getch();
}
Enter String 2: xyz
Result = -1
0 = both strings are equal
-1 = if the ASCII value of first character is less than second.
1 = if the ASCII value of first character is greater than second. (see ASCII table)
No comments:
Post a Comment
Feel free to ask us any question regarding this post