Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Declaring a String
3.
By using the char array
4.
By using the string literal
5.
Inputting a String
6.
Important Functions
6.1.
strcpy(string1,string2) 
6.2.
strcat(string1,string2) 
6.3.
strlen(string1) 
6.4.
strcmp(string1,string2) 
6.5.
strrchr(string1,ch) 
6.6.
strstr(string1,string2) 
7.
FAQs
8.
Key Takeaways:
Last Updated: Mar 27, 2024

Strings in C

gp-icon
Data structures & algorithms (Beginner to Intermediate)
Free guided path
13 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

In any programming language like in C, C++, when we need to store a sequence of characters like if we want to store a student's name or the name of a car, we use a character array of some predefined size. A string is defined as a one-dimensional array of characters that always terminates with a special character ‘\0’ (NULL). Since each character takes one byte of memory and a string always terminates with a null character, the size of the character array used to store the string is always one greater than the number of characters in the string/word to be stored.

Also See, Sum of Digits in C and C Static Function

Declaring a String

There are two ways in which we can declare a string in the C programming language. The key difference between them is that in one method, we need to add the null character at the end explicitly, and in the other, it is added by the compiler automatically. The following are the two methods:

You can also read about the dynamic arrays in c, and Tribonacci Series

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

By using the char array

When declaring a string using the char array, the programmer has to add the null character at the end of the string. A char array can be reassigned to another set of characters.

 

Example

#include <stdio.h>
#include<string.h>
  
int main()
{
  char arr[]={'H','e','l','l','o',' ','W','o','r','l','d','\0'};
  printf("The string is : %s",arr);
  
}

Output

The string is : Hello World

By using the string literal

When declaring a string using a string literal, the compiler automatically adds the null character at the end of the string. A string literal once assigned cannot be reassigned to another set of characters.

Example

#include <stdio.h>
#include<string.h>
  
int main()
{
  char arr[]="Hello World";
  printf("The string is : %s",arr);
  
}

Output

The string is : Hello World

Inputting a String

Example

#include<stdio.h>  
#include<string.h>

int main()  
{  
    char string[20];  
    printf("Enter the string : ");  
    scanf("%[^\n]s",string);  
    printf("Entered string is : %s",string);  
}  

Output

Enter the string : Hello World!
Entered string is : Hello World!

Explanation

In C language, in order to accept input from the user, scanf() is used. We have not used ‘&’ with string (char array name) because the ‘&’ operator is used to provide the address of the variable to the scanf() in order to store the values entered by the user into the memory.

While reading inputs from the user, it must be taken into consideration that we must specify whether to take space-separated strings or not. In the above code, we have used ‘[^\n]’ in the scanf() to instruct the compiler to store the string till a new line is encountered. If we don't use [^\n] in the above code, only the characters before the first space will be considered and stored in the string.

While taking string inputs, it is preferred to use the gets() function, which is an inbuilt function in the ‘string.h’ header file. The gets() function is capable of receiving one string at a time, and the gets() function reads input until it encounters a newline or end of file (EOF). The main reason why we don't prefer scanf() for taking string inputs is that while using scanf(), the compiler doesn't perform any bound checking, that is, if the length of the string exceeds the size of the character array, then some important data is overwritten. You can practice it on an online c editor for better understanding.

Important Functions

strcpy(string1,string2) 

strcpy stands for string copy. The strcpy() function takes two strings as its arguments and copies string2 into string1.

Example

#include<stdio.h>  
#include<string.h>

int main()  
{ 
  char string1[]="Hello";
  char string2[]="Ninja";

  printf("String-1 before strcpy() function : %s",string1);
  strcpy(string1,string2);
  printf("\nString-1 after strcpy() function : %s",string1);

}

Output

String-1 before strcpy() function : Hello
String-1 after strcpy() function : Ninja

 

strcat(string1,string2) 

strcat stands for string concatenation. The Strcat() function takes two strings as its arguments and concatenates the string2 at the end of string1.

Example

#include<stdio.h>  
#include<string.h>

int main()  
{  
  char string1[]="Hello ";
  char string2[]="Coders!!";

  printf("String-1 before concatenation : %s",string1);
  strcat(string1,string2);
  printf("\nString-1 after concatenation : %s",string1);
}  

Output

String-1 before concatenation : Hello 
String-1 after concatenation : Hello Coders!!

 

strlen(string1) 

strlen stands for string length. The strlen() function takes one string as its argument and returns the length of the string1.

Example

#include<stdio.h>  
#include<string.h>

int main()  
{ 
  char string1[]="Coding Studio";

  int len=strlen(string1);
  printf("Length of %s is %d",string1,len);
}

Output

Length of CodingStudio is 13

 

strcmp(string1,string2) 

strcmp stands for string compare. The strcmp() function takes two strings as its argument and compares them lexicographically. It returns 

  • A value 0 if both strings are identical 
  • A value greater than zero if the first not matching character in string1 has a greater ASCII value than the corresponding character in string2 
  • A value less than zero if the first not matching character in string1 has an ASCII value lesser than the corresponding character in string2.

Example

#include<stdio.h>  
#include<string.h>

int main()  
{ 
  char string1[]="Ninja";
  char string2[]="Ninja";

  int val=strcmp(string1,string2);
  printf("On comparing %s and %s the value returned is %d",string1,string2,val);
}

Output

On comparing Ninja and Ninja the value returned is 0

 

strrchr(string1,ch) 

The strrchr() function takes two arguments : a string and a character. It is used to return a pointer to the last occurrence of the character ch in string1.

Example

#include<stdio.h>  
#include<string.h>

int main()  
{  
  char string1[]="Coding Ninjas!";
  char ch='j';

  char *val=strrchr(string1,ch);
  printf("The string after last occurrence of %c in the string %s is %s",ch,string1,val);
}  

Output

The string after last occurrence of j in the string Coding Ninjas! is jas!

 

strstr(string1,string2) 

The strstr() function takes two strings as its arguments. It is used to return a pointer to the first occurrence of string2 in string1.

Example

#include<stdio.h>  
#include<string.h>

int main()  
{  
  char string1[]="Hi Ninjas,Work Hard!!!";
  char string2[]="Ninjas";

  char *val=strstr(string1,string2);
  printf("The string after the first occurrence of %s in %s is : %s",string2,string1,val);
}  

Output

The string after the first occurrence of Ninjas in Hi Ninjas,Work Hard!!! is : Ninjas,Work Hard!!!

 

You can also check out Reverse A String In C , Short int in C Programming 

Must Read Decision Making in C

FAQs

  1. Is it necessary to specify the character array size while declaring a string?
    No, it is not necessary to specify the character array size while declaring a string.
     
  2. What happens if we don't have a null character at the end of the string?
    Some of the functions which are used with strings require a null char. In the case of the absence of a null character, the program will terminate with a Segmentation Fault since the pointer tries to access memory that is not owned by the program.
     
  3. What is the difference between scanf() and gets() while taking input?
    The scanf() function can read multiple values of different data types, whereas the gets() function can read-only character string data.

Key Takeaways:

In this blog, we have covered the following topics:

  • We first discussed what strings in C programming languages are?
  • Then we discussed the different ways of declaring a string in the C programming language.
  • Finally, we discussed how to input a string and some of the important functions used with strings in the C language.

C language has many Data structures to offer, which are used for various different purposes like arrays for storing continuous data, etc.

Questions related to strings are asked frequently in personal interviews, you can practice and learn more about them from this.

Check out this article - C++ String Concatenation

Recommended problems -

 

Almost every programming language supports string and its functions, you can learn how to convert an array into a string in any language from this.

In order to write a structured code, knowledge of structuresfunctions, and different data types is very important.

Next article
String Functions
Guided path
Free
gridgp-icon
Data structures & algorithms (Beginner to Intermediate)
13 chapters
109+ Problems
gp-badge
Earn badges and level up
Live masterclass