String

String are actually one-dimensional array of characters. The difference in character array and string is the string is terminated with a special character ‘\0’. When the compiler encounters a sequence of characters enclosed in the double quotation marks. Each character in the array occupies one byte of memory and the last character must always be 0.

Below is the basic syntax for declaring a string.

char str_name[size];

There are two ways to declare a string in c language.

  • By char array
  • By string literal

let’s see the example of declaring string by char array in c language.

char ch[]={‘t’, ‘e’, ‘c’, ‘h’, ‘n’, ‘i’, ‘c’, ‘a’, ‘l’, ‘f’, ‘u’, ‘n’, ‘d’, ‘a’, ‘\0’};

let’s see the example of declaring string by string literal in C language.

char ch[]=”technical funda”;

String example in C

#include<stdio.h>  
#include <string.h>    
int main(){    
  char ch[15]={'t', 'e', 'c', 'h', 'n', 'i', 'c', 'a', 'l', 'f', 'u', 'n', 'd', 'a', '\0'};    
   char ch2[15]="technicalfunda";    
    
   printf("Char Array Value is: %s\n", ch);    
   printf("String Literal Value is: %s\n", ch2);    
 return 0;    
}

Output

Char Array Value is: technicalfunda
String Literal Value is: technicalfunda

Traversing String

Traversing string is the most important aspects in any of the programming languages. We know the length of the array to traverse an integer array, now those we use the null character in the case of string to identify the end and the string and terminate the loop.

There are two ways to traverse a string

  • By using the length of string
  • By using the null character

Let’s see the example of using the length of the string

#include<stdio.h>  
void main ()  
{  
    char s[10] = "technical";  
    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 3

Let’s see the example of using the null character

#include<stdio.h>  
void main ()  
{  
    char s[10] = "technical";  
    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 3

Submit your review
1
2
3
4
5
Submit
     
Cancel

Create your own review

The Technical Funda
Average rating:  
 0 reviews