Tutorial Playlist
Following their ease of conveying information from program to user, Strings play a crucial role in C programming. You can implement strings in C using character arrays, enabling you to perform standard operations. Alternatively, you can implement strings using pointers because character arrays behave as pointers.
Before going through the details of C string declaration, let’s first get an overview of a string.
A string refers to a collection of characters (including numerals, symbols, letters and punctuations) represented in a regular, uniform sequence. A string in C is a sequence of characters terminated with a NULL character '\0'.
Here’s an example of C string declaration.
char str[] = "Programming.\0"; |
Strings in C are enclosed within double quotes(" "), and characters are enclosed within single quotes(' '). Whenever the compiler detects a sequence of characters enclosed with double quotes marks, by default, it adds a null character (\0) at the end.
A string literal means a sequence comprising zero or multiple multibyte characters enclosed within double quotes. For example, "language".
The following points justify the importance of C strings:
Here are the four methods to initialise a string under C programming:
1. Assign a string literal with size
A string literal can be assigned to any character array. Make sure that the array’s size is one more compared to the string literal length. For example, if you want to store a string of size n, the array’s size should be- n+1.
Here is a typical string in C example.
char str[10] = "Software."; |
Although the string length is 9, we set the size to 10 to accommodate Null Character. The compiler automatically adds the Null character(\0) while closing. If the array of strings in C can’t accommodate the whole string, it only receives characters according to its space. Let’s look at the following example to understand it:
char str[3] = "Software."; |
Output:
Sof |
As seen in the example above, the defined length of the array is 3, so the program only prints the first three elements.
2. Assign a string literal without size
You can directly allot a string literal to any character array without specifying the size, as the compiler determines the size during compile time automatically. Here’s how.
char str[] = "Software."; |
In the above example, the size is not defined. Here, "str" behaves as a pointer since it is an array.
3. Assign character by character with size
You can assign a string based on each character. But make sure to terminate the last character with '\0'. Here’s an example:
char str[10] = {'S', 'o', 'f', 't', 'w', 'a', 'r', 'e' ,'.','\0'}; |
4. Assign character by character without size
You can allot each character with the null character while closing. The compiler will automatically determine the string’s size
char str[] = {'S', 'o', 'f', 't', 'w', 'a', 'r', 'e' '.','\0'}; |
Accessing C Strings
The process of accessing C strings incorporates retrieving and manipulating individual characters from a null-terminated character array. A few common ways to access C strings are:
The data type of string in C is character. C doesn’t directly support string as a data type. Thus, you should use character arrays to display a string in C. Here’s the syntax of C string declaration:
char variable[array_size]; |
Based on this syntax, let’s declare the strings.
char str[10]; |
String Literal Declaration
A string literal in C refers to a sequence of characters contained in double quotation marks (" "). For example,
char* str = "We are programmers."; |
A character array indicates a continuous sequence of characters, usually terminated by a null character ('\0'). In C, you can declare and use character arrays as follows:
char str1[] = {'L', 'e', 'a', 'r', 'n', 'i', 'n', 'g', '\0'}; |
Pointer Declaration
In C, pointers are variables that hold memory addresses. The following syntax helps you to declare and use pointers in C:
int num = 42; |
If you want to read strings in C, you can use the scanf function or its safer alternative, fgets. The scanf function lets you read input from the standard input stream. Its syntax is:
The fgets function reads a line of input from any standard input stream and saves it in a character array. Here’s its syntax.
scanf("%s", str); |
fgets(str, sizeof(str), stdin); |
If you want to write or output C strings, you can use the printf function or any other output functions such as fputs or puts.
Syntax of printf function:
Syntax of printf function:
printf("String: %s\n", str); |
Syntax of puts function:
puts(str); |
Syntax of fputs function:
fputs(str, stdout); |
The scanf() is used for string input in C. It reads a sequence of characters up till it detects whitespace (like tab, space, newline, etc.). The following example demonstrates how scanf string in C works.
char str[40]; |
Suppose we provide the given input:
We are learning C programming |
We get the output:
We |
As seen from the above example, the scanf() function stops accepting input if it encounters whitespace. %s refers to a format specifier used to accept input and display output strings in C.
The strlen() function returns the length of a string without the null character ('\0').
This function appends one string to the termination of another.
It copies the data of one string to another.
This function draws a comparison between two strings lexicographically. If the first string is greater compared to the second one, it returns a positive value, 0 if both strings are equal, and a negative value if the initial string is smaller than the second one.
The scanf() function can’t read strings with spaces because it halts the reading process automatically whenever it detects whitespace. If you want to read and print strings comprising whitespace, you can use the fgets() and puts() functions.
fgets():
This function reads a specific number of characters. It is declared as:
fgets(name_of_string, number_of_characters, stdin); |
Let’s understand each parameter of the above syntax.
name_of_string*: It refers to the variable that stores the string.
number_of_characters: It specifies the maximum length of the string that must be read.
stdin: It is the file handle from where the string will be read.
puts():
It is used to display strings. Here’s its syntax.
puts(name_of_string); |
Here, name_of_string is the variable to store the string.
The following example program uses both the above string functions in C with examples.
#include <stdlib.h> |
Input:
Please enter a string: I am a lucky person |
Output:
The entered string is: I am a lucky person |
As seen from the above example, the input string has the whitespace. However, the combination of fgets() and puts() functions lets the program store and display the whole string.
Passing strings to functions
The strings are merely character arrays. So, you can pass strings to function the way you pass an array to a function. You can do this either using a pointer or an array. Here’s an example program that demonstrates how to pass strings to functions.
#include <stdio.h> |
Output:
The string is : I like C programming |
As seen from the above example, the string str is passed to an array and also to a pointer.
The strings in C are depicted using character arrays acting as pointers. So, you can use pointers to perform string operations.
#include <stdlib.h> |
Output:
So. |
String Example in C
The following program illustrates how C handles string literals using arrays and pointers.
#include <stdio.h> |
Output:
Now we will look at how C handles string literals using array. |
When C handles the string literal using an array, it displays the whole input string. Also, it allows the substitution of elements of the array. When C handles string literal using a pointer, it, too, displays the whole input string. However, it doesn’t allow the substitution of characters.
Character Array and String Literal: Differences
Character Array | String Literal |
The declaration of character arrays involves specifying char data type followed by the array name and size. | The declaration of string literals happens by enclosing the sequence of characters in double quotation marks. |
Character arrays are mutable, so you can alter individual characters in the array. | Typically, string literals are stored in read-only memory and are immutable. If you directly try to alter a string literal, it may lead to undefined behaviour. |
Character arrays are either allocated on the stack or dynamically allocated through malloc or associated functions. Hence, they increase the flexibility of memory management. | String literals are stored in read-only memory, usually in a compiler-managed data segment. |
Character arrays should be explicitly null-terminated by specifying a null character ('\0') at the end of the string. | String literals are automatically null-terminated. |
You can explicitly specify the size of a character array. Hence, you can control the memory allocated for the particular string. | String literals' sizes are automatically decided as per the length of the enclosed string (including the null character). |
Applications of C Strings
Here are a few common applications of C Strings
Strings in C simplify accessing, manipulating, and storing information. They improve the efficiency of compile-time allocation. Moreover, they provide the easiest possible storage that conserves space.
Understanding the basics of string in C is not adequate, as you also need to practice it and try applying it in different scenarios. Adopting this approach will help you master all essential concepts of string in C.
While going through tutorials to strengthen your fundamentals, you can enrol in upGrad’s Master of Science in Computer Science program, offered by Liverpool John Moores University and skyrocket your software development career. It lets you learn software development using various programming languages, helping you excel in the field of development!
Q. How can you pass a string to functions in C?
You can pass a string to functions as a pointer or a character array.
Q. What is the limitation while reading a string in C?
The scanf() function reads strings in C, but it only reads until it runs into whitespace.
Q. What are string manipulation functions?
The string manipulation functions help you to compare or manipulate strings. They have the str prefix. Some of the examples of these functions are strlen(), strcat(), strcmp(), strcpy(), stricmp(), strchr(), etc.
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...