Traversing String in C Language
Categories: C language
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.
Hence, there are two ways to traverse a string.
1. By using the length of string
2. By using the null character.
Let's discuss each one of them.
Using the length of string
Let's see an example of counting the number of vowels in a string.
#include<stdio.h>
void main ()
{
char s[11] = "javatpoint";
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
The number of vowels 4
Using the null character
Let's see the same example of counting the number of vowels by using the null character.
#include<stdio.h>
void main ()
{
char s[11] = "javatpoint";
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);
}
Output
The number of vowels 4