Strings in C
Strings in C
Definition
#include <stdio.h>
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}
Output:
Greeting message: Hello
Example-2:
// C program to illustrate strings
#include<stdio.h>
int main()
{
// declare and initialize string
char str[] = “Hello";
// print string
printf("%s",str);
return 0;
}
Output:
Hello
sample program to read a string from user:
#include<stdio.h>
int main()
{
// declaring string
char str[50];
// reading string
scanf("%s",str);
// print string
printf("%s",str);
return 0;
C supports a wide range of functions that manipulate
null-terminated strings −
Sr.No. Function & Purpose
strcpy(s1, s2);
1
Copies string s2 into string s1.
strcat(s1, s2);
2
Concatenates string s2 onto the end of string s1.
strlen(s1);
3
Returns the length of string s1.
strcmp(s1, s2);
4 Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
s1>s2.
The following example uses some of the above-mentioned
functions −
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
OUTPUT:
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
C program to compare the two strings
#include <stdio.h>
#include<string.h>
int main()
{
char str1[20]; // declaration of char array
char str2[20]; // declaration of char array
int value; // declaration of integer variable
printf("Enter the first string : ");
scanf("%s",str1);
printf("Enter the second string : ");
scanf("%s",str2);
// comparing both the strings using strcmp() function
value=strcmp(str1,str2);
if(value==0)
printf("strings are same");
else
printf("strings are not same");
return 0;
String comparison without using strcmp() function
#include <stdio.h>
int compare(char[],char[]);
int main()
{
char str1[20]; // declaration of char array
char str2[20]; // declaration of char array
printf("Enter the first string : ");
scanf("%s",str1);
printf("Enter the second string : ");
scanf("%s",str2);
int c= compare(str1,str2); // calling compare() function
if(c==0)
printf("strings are same");
else
printf("strings are not same");
return 0;
}
// Comparing both the strings.
int compare(char a[],char b[])
{
int flag=0,i=0; // integer variables declaration
while(a[i]!='\0' &&b[i]!='\0') // while loop
{
if(a[i]!=b[i])
{
flag=1;
break;
}
i++;
}
if(flag==0)
return 0;
else
return 1;
}