Array and Strings
Array and Strings
Strings in C
Strings are defined as an array of characters. The difference between a character array and a string
is the string is terminated with a special character ‘\0’.
Declaration of strings: Declaring a string is as simple as declaring a one dimensional array.
Syntax:
char str_name[size];
In the above syntax str_name is any name given to the string variable and size is used define the
length of the string, i.e the number of characters strings will store. Please keep in mind that there
is an extra terminating character which is the Null character (‘\0’) used to indicate termination of
string which differs strings from normal character arrays.
Example:
char str[5];
Initializing a String:
Below is an example to declare a string with name as str and initialize it with “FYIT Class”
char str[] = " FYIT Class s";
OR
char str[50] = " FYIT Class ";
OR
char str[] = {'F','Y','I','T', ' ','C','l','a','s','s','\0'};
OR
char str[50] = {'F','Y','I','T', ' ','C','l','a','s','s','\0'};
str[0] str[1] str[2] str[3] str[4] str[5] str[6] str[7] str[8] str[9] str[10]
F Y I T C l a s s '\0'
Note:
String can also be initialized using pointers as:
char *str = "abcd";
Example 1:
// C program to illustrate strings
#include<stdio.h>
int main()
{
// declare and initialize string
char str[] = "Saurabh";
// print string
printf("%s",str);
return 0;
}
Output:
Saurabh
Example 2:
Below is a 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("You have entered: %s",str);
return 0;
}
Example 3:
Find the Frequency of Characters a number of times character present
#include <stdio.h>
int main()
{
char str[100], ch;
int i, frequency = 0;
return 0;
}
Output
Example 4:
C program to read line of text using gets() and puts().
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}
Output
Enter name: Saurabh
Name: Saurabh
String functions in C:
C supports a large number of string handling functions in the standard library"string.h".
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
return 0;
}
Output:
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10