Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

String Program in C

Last Updated on December 28, 2022 by Prepbytes

The one-dimensional array of characters that is ended by a null ‘\0’ is the description of a string. Text, such as words or phrases, can be edited using a character array or string. The last character in the array must always be 0, and each character takes up one byte of memory. Since there is no other way to tell where a string stops, the termination character ‘\0’ is crucial. When a string is defined as char s[10], the memory initialization of character s[10] is implicitly set to null.

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

  • By char array
  • By string literal

Let’s see the example of declaring a string by char array in C language.

char ch[10]={'P', 'r', 'e', ‘p’, 'B', 'y', 't', 'e', 's', '\0'};  

While declaring a string, size is not mandatory. So we can write the above code as given below:

char ch[]={'P', 'r', 'e', ‘p’, 'B', 'y', 't', 'e', 's', '\0'};  

We can also define the string by the string literal in C language. For example:

char ch[]="PrepBytes";

In such a case, ‘\0’ will be appended at the end of the string by the compiler.

Difference between a char array and a string literal

There are two main differences between char array and literal.

  • The null character ‘\0’ is inserted internally by the compiler in the case of a character array, but we must add it ourselves at the end of the array in this case.
  • The characters in the array may be changed, unlike the string literal, which cannot be changed to another set of characters.

String Example in C
Let’s have a look at a straightforward example where a string is defined and printed. In the C language, the format specifier for the string is ‘%s’.

Code Implementation:

#include<stdio.h>  
#include <string.h>    
int main(){    
  char ch[11]={'P', 'r', 'e', 'p', 'B', 'y', 't', 'e', 's', '\0'};    
   char ch2[11]="PrepBytes";    
    
   printf("Char Array Value is: %s\n", ch);    
   printf("String Literal Value is: %s\n", ch2);    
 return 0;    
}

Output:

Char Array Value is: PrepBytes
String Literal Value is: PrepBytes

Traversing String

One of the most crucial aspects of every programming language is traversing the string. An extremely large text may require manipulation, which may be accomplished by traversing the text. The traversal of a string differs significantly from the traversal of an integer array. In contrast to strings, where we may use the null character to mark the end of the text and finish the loop, numeric arrays require us to know their length before we can traverse them.
There are therefore two methods for traversing a string.

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

Let’s discuss each one of them.

Using the length of the string

Let’s see an example of counting the number of vowels in a string.

Code Implementation:

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

Using the null character

Let’s see the same example of counting the number of vowels by using the null character.

Code Implementation:

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

Accepting string as the input

Up until this point, we have used scanf to receive user input. It may also be applied to strings, although in a different circumstance. Take a look at the code below, which saves the string whenever a space is detected.

Code Implementation:

#include<stdio.h>  
void main ()  
{  
    char s[20];  
    printf("Enter the string\n");  
    scanf("%s",s);  
    printf("You entered: %s",s);  
}

Input:

PrepBytes is awesome

Output:

Enter the string
You entered: PrepBytes

It is clear from the output that the above code will not work for space separated strings. To make this code working for the space separated strings, the minor changes required in the scanf function, i.e., instead of writing scanf("%s",s), we must write: scanf("%[^\n]s",s) which instructs the compiler to store the string s while the new line (\n) is encountered. Let’s consider the following example to store the space-separated strings.

Code Implementation:

#include<stdio.h>  
void main ()  
{  
    char s[20];  
    printf("Enter the string\n");  
    scanf("%[^\n]s",s);  
    printf("You entered %s",s);  
}

Input:

PrepBytes is awesome

Output:

Enter the string
You entered PrepBytes is awesome

Here we must also notice that we do not need to use the address of (&) operator in scanf to store a string since string s is an array of characters and the name of the array, i.e., s indicates the base address of the string (character array) therefore we need not use & with it.

Some important points

However, there are the following points that must be noticed while entering the strings by using scanf.

  • The compiler doesn’t perform bounds checking on the character array. Hence, there can be a case where the length of the string can exceed the dimension of the character array which may always overwrite some important data.
  • Instead of using scanf, we may use gets() which is an inbuilt function defined in a header file string.h. The gets() is capable of receiving only one string at a time.

Other C Programs

C Program for Binary Search
C Program to Add Two Numbers
C Program to Calculate Percentage of 5 Subjects
C Program to Convert Binary Number to Decimal Number
C Program to Convert Celsius to Fahrenheit
C Program to Convert Infix to Postfix
C Program to Find Area of Circle
C Program to Find Roots of Quadratic Equation
C program to Reverse a Linked List
C program to reverse a number
Ascending Order Program in C
Menu Driven Program For All Operations On Doubly Linked List in C
C Program for Armstrong Number
C Program For Merge Sort For Linked Lists
C program for performing Bubble sort on Linked List
Hello World Program in C
Perfect Number Program in C
Leap Year Program in C
Odd Even Program in C
Selection Sort Program in C
Linear Search Program in C
While Loop Program in C
C Program to Swap Two Numbers
Calculator Program in C Language
Simple Interest Program in C
Compound Interest Program in C
Priority Scheduling Program in C
Doubly Linked List Program in C
FCFS Scheduling Program in C
Insertion Sort Program in C
Singly Linked List Program in C
Star Program in C

Leave a Reply

Your email address will not be published. Required fields are marked *