Tutorial Playlist
As an integral part of any programming language, strings in C play a significant role in storing and manipulating sequences of characters. Strings in C are depicted as an array of characters that concludes with a null character ('\0'). However, C does make up for this by offering a wide selection of string functions via the standard library, enhancing your code's clarity and efficiency.
This in-depth article will explore various string functions in C, provide examples and explain each section comprehensively. We'll delve into a range of concepts, including the array of strings in C, scanf string in C, and string input in C.
A C string is declared similarly to an array. Here's a basic demonstration:
char str[50] = "Hello, World!"; |
In this instance, str represents an array of characters, which is initialized using the string "Hello, World!". Essentially, the string is stored character by character in each index of the array, ending with a null character.
Before delving into the various string functions in C, it's essential to understand how to prepare your program to use these functions.
In C programming, there's a standard library <string.h> which contains various functions to perform operations on strings. To use the functions declared in this library, you have to include them in your program. The inclusion is done with the preprocessor directive #include.
Here's how you include the <string.h> library in your C program:
#include <stdio.h> |
In the code snippet above, <stdio.h> is the standard input-output library in C, which contains functions like printf() and scanf(). The <string.h> library, on the other hand, contains various string manipulation functions like strcpy(), strlen(), strcat(), etc.
Here is an example illustrating the use of fundamental string functions:
#include <stdio.h> |
In this code:
While C doesn't natively support a "String" data type, it's common to create strings using an array of characters. The scanf function can be used for string input in C, as demonstrated below:
#include<stdio.h> |
In this code, we declare a character array str of size 100, prompting the user to input a string.
Character arrays are simply arrays that store individual characters. This example creates an array of five characters:
char c[5]; |
The terms "character array" and "string" are often used interchangeably in C, but there are key differences between them.
A character array in C is simply an array of characters. You can declare it and initialize it with individual characters.
On the other hand, a string in C is a special type of character array that ends with a null character (\0). The null character is used to mark the end of the string.
There are multiple ways to initialize strings in C. Here's a basic illustration:
char str1[] = "Hello"; // String literal initialization |
In the first declaration, str1 is automatically sized to hold the string literal and is initialized with "Hello". The second declaration manually specifies the array's size and initializes it with individual characters, including the null character at the end.
Individual characters within a string can be accessed using their array index:
char str[] = "Hello"; |
In this code, we're accessing the second character (at index 1, since C arrays are 0-indexed) of the string and printing it to the console.
Let's go over some of the most commonly used string manipulation functions.
The strlen() function calculates the length of a string excluding the null terminating character.
Example:
#include <stdio.h> |
This code asks the user for a string input, which it then measures using strlen(), printing out the length of the string to the console.
The strcat() function concatenates (joins end-to-end) two strings.
Example:
#include <stdio.h> |
In this code, we're getting two strings as input from the user. We then concatenate the second string to the end of the first string using strcat(), effectively modifying the first string.
The strcpy() function is used to copy the content of one string into another.
Example:
#include <stdio.h> |
In this example, we copy the content of the source string into the destination string using strcpy(). The content of the source string remains unchanged, and the destination string becomes identical to the source string.
The strcmp() function is used to compare two strings. It returns 0 if the strings are identical, a negative value if the first string is less than the second, and a positive value if the first string is greater than the second.
Example:
#include <stdio.h> |
In this code, we take two strings from the user. We then use strcmp() to compare these strings and print a message depending on whether the strings are equal or not.
The strncat() function is similar to strcat(), but it concatenates only the first n characters of the second string to the first string.
Example:
#include <stdio.h> |
In this code, we get two strings and an integer n from the user. We then concatenate the first n characters of the second string to the first string using strncat().
The strncpy() function is used to copy the first n characters of one string into another.
Example:
#include <stdio.h> |
In this example, we copy the first n characters of the source string into the destination string using strncpy(). The remaining characters in the destination string, if any, are not modified.
The strncmp() function is used to compare the first n characters of two strings. It works in the same way as strcmp(), but the comparison stops after n characters.
Example:
#include <stdio.h> |
In this code, we compare the first n characters of two user-entered strings using strncmp() and print a message depending on the result.
The strchr() function is used to find the first occurrence of a character in a string. It returns a pointer to the character's location in the string, or NULL if the character is not found.
Example:
#include <stdio.h> |
In this code, we find the first occurrence of a user-entered character in a user-entered string using strchr().
The strstr() function is used to find the first occurrence of a substring in a string. It returns a pointer to the beginning of the located substring, or NULL if the substring is not found.
Example:
#include <stdio.h> |
In this code, we find the first occurrence of a user-entered substring in a user-entered string using strstr().
The strtok() function is used to split a string into a series of tokens using a delimiter.
Example:
#include <stdio.h> |
In this example, we split a user-entered string into tokens using a user-entered delimiter with strtok(). Each token is then printed on a new line.
The sscanf() function is used to read formatted input from a string.
Example:
#include <stdio.h> |
In this code, we read two integers from a string using sscanf(). The read values are then printed to the console.
String formatting functions help to format strings in C. Let’s explore some of these functions.
The sprintf() function is used to store formatted data as a string.
Example:
#include <stdio.h> |
In this code, we're storing the formatted string "Sum of 10 and 20 is 30." into the buffer using sprintf().
The printf() function is used to print formatted data to stdout (the console, by default).
Example:
#include <stdio.h> |
In this example, we're printing the formatted string "Sum of 10 and 20 is 30." directly to the console using printf().
The fprintf() function is used to print formatted data to a file.
Example:
#include <stdio.h> |
In this code, we're printing the formatted string "Sum of 10 and 20 is 30." to a file named "test.txt" using fprintf().
String functions in C play a significant role in various fields, including:
String functions in C offer a powerful and flexible way to manipulate, process, and interact with character strings. Understanding these functions will significantly enhance your capability to write efficient and powerful C programs. Now it's your turn to experiment with these functions. Practice makes perfect!
Which is why enrolling in upGrad’s DevOps Engineer Bootcamp can greatly contribute to the well-being of your professional career, helping skyrocket your professional growth!
A string in C can be referred to as a character array ending with a null character (\0). To declare a string in C, you can either initialize it directly: char str[] = "Hello"; or declare an array to hold the string: char str[100]; and then input the string using functions like gets(), scanf(), etc.
Yes, you can perform various operations on strings in C using string functions. These operations include copying a string (strcpy()), concatenating two strings (strcat()), comparing two strings (strcmp()), finding the length of a string (strlen()), and many more.
You can take string input in C using functions like scanf(), gets(), fgets(), etc. Be careful while using scanf(), as it terminates the input on encountering a space. So, for a sentence input, gets() or fgets() are more suitable.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...