Lecture 31
Lecture 31
Lecture 31
Strings: Concepts
A String in C programming is a sequence of characters terminated with a null
character ‘\0’. The C String is stored as an array of characters. The difference
between a character array and a C string is that the string in C is terminated with a
unique character ‘\0’.
Declaring a string in C is as simple as declaring a one-dimensional array. Below is the
basic syntax for declaring a string.
char string_name[size];
In the above syntax string_name is any name given to the string variable and size is
used to define the length of the string, i.e the number of characters strings will store.
There is an extra terminating character which is the Null character (‘\0’) used to
indicate the termination of a string that differs strings from normal character
arrays.
A string in C can be initialized in different ways. We will explain this with the help of
an example. Below are the examples to declare a string with the name str and
initialize it with “JIETforStudents”.
We can initialize a C string in 4 different ways which are as follows:
1. Assigning a String Literal without Size
String literals can be assigned without size. Here, the name of the string str acts as a
pointer because it is an array.
char str[] = "JIETforStudent";
Note that, the string is read only till the whitespace is encountered.
The C language comes bundled with <string.h> which contains some useful string-
handling functions. Some of them are as follows:
Function Name Description
Compares the first string with the second string. If strings are the
strcmp(str1, str2)
same it returns 0.
Concat s1 string with s2 string and the result is stored in the first
strcat(s1, s2)
string.
Traversing String
Traversing the string is one of the most important aspects in any of the programming languages.
We may need to manipulate a very large text which can be done by traversing the text. Traversing
string is somewhat different from the traversing an integer array. We need to know the length of
the array to traverse an integer array, whereas we may use the null character in the case of string
to identify the end the string and terminate the loop.
#include<stdio.h>
void main ()
{
char s[11] = "JIETCOLLEGE";
int i = 0;
int count = 0;
while(i<11)
{
if(s[i]=='A' || s[i] == 'E' || s[i] == 'I' || s[i] == 'U' || s[i] == 'O')
{
count ++;
}
i++;
}
printf("The number of vowels %d",count);
}
Output
#include<stdio.h>
void main ()
{
char s[11] = "JIETCOLLEGE";
int i = 0;
int count = 0;
while(s[i] != NULL)
{
if(s[i]=='A' || s[i] == 'E' || s[i] == 'I' || s[i] == 'U' || s[i] == 'O')
{
count ++;
}
i++;
}
printf("The number of vowels %d",count);