Last Updated on June 6, 2023 by Mayank Dham
The definition of C string , how to declare a string, string definition in C and what is string in C language are all covered in this article. With examples, it goes over the many ways to initialize strings. It discusses how to read text from a user and how to read text with whitespace. Also addressed is how to represent strings as pointers and send them to functions. It covers what we learned in the article by going over an example of a C String. Finally, it compares and contrasts character arrays and string literals.
String in C Language?
Strings are useful for communicating information from the program to the program user and, thus, are a part of all programming languages and applications. They are implemented with character arrays that behave like usual arrays with which we can perform regular operations, including modification. Another way of implementing strings is through pointers since character arrays act as pointers. These pointers point to string literals and cannot be modified as string literals are stored in the read-only memory by most compilers. Thus, any attempt at modifying them leads to undefined behavior.
String Definition in C
A string is a group of characters, such as letters, numbers, symbols, and punctuation marks, that are arranged in a linear fashion. A string in C is a group of characters that is finished with the NULL character "0." For instance:
char str[] = "PrepBytes.\0";
Like many other programming languages, C encloses strings in double quotes ("") while enclosing characters in single quotes (”). A null character (\0) is automatically added at the conclusion when the compiler discovers a string of characters contained in double quotation marks.
So, the string is stored in this way:
A group of zero or more multibyte characters surrounded in double quotes, such as "abc," is referred to as a string literal. String literals cannot be changed (and are placed in read-only memory). Any attempt to change their values leads to behavior that is undefined.
How to Declare String in C
A character-based array known as a String in the C programming language. In contrast to other programming languages like C++, C does not natively provide the string data type. Therefore, in order to show a string in C, character arrays are required. Declaring a string in C generally looks like this:
char variable[array_size];
Consequently, the traditional declaration can be expressed as follows::
char str[5];
char str2[50];
We must always take into consideration the extra space that the null letter (\0) occupies.
Highlights
In C, strings are declared using character arrays.
Their general syntax is as follows:
char variable[array_size];
Initializing C String
There are four methods of initializing a string in C:
1. Assigning a string literal with size
Directly assigning a string literal to a character array is possible as long as the array size is at least one greater than the string literal original length.
Note: The null character requires one additional space, therefore we must always take it into consideration when calculating the initial size. Setting the initial size to be n+1 will allow us to store a string of size n.
For example:
char str[8] = "PrepBytes.";
Although this string should be 10 characters long, we kept the size at 11 to include the Null character. The Null character (\0) is automatically added at the end by the compiler.
Note: If the string is too long for the array, it only accepts characters based on available space. For instance:
char str[3] = "PREPBYTES.";
printf("%s",str);
Output
PRE
2. Assigning a string literal without size
Another option is to simply assign a string literal with no size to a character array. At compile time, the compiler automatically calculates the size.
char str[] = "PREPBYTES";
The important thing to keep in mind is that because this string is an array and is called "str," it functions as a pointer.
3. Assigning character by character with size
A string can also be assigned character per character. But it’s crucial to set the final character to be ‘0’. For instance:
char str[11] = {'P', 'R', 'E', 'P', 'B', 'Y', ‘T’, ‘E’, ‘S’, '.','\0'};
4. Assigning character by character without size
We also assign character by character with the Null Character at the end, similar to assigning straight without regard to size. The length of the string will be determined automatically by the compiler.
char str[] = {{'P', 'R', 'E', 'P', 'B', 'Y', ‘T’, ‘E’, ‘S’, '.','\0'};
Highlights: There are four methods of initializing a string in C:
1. Assigning a string literal with size.
2. Assigning a string literal without size.
3. Assigning character by character with size.
4. Assigning character by character without size.
Assign Value to Strings
Once they have been declared, character arrays cannot be given a string literal using the ‘=’ operator.
char str[100];
str = "String.";
Since assignment operations are not supported after strings are declared, this will result in a compilation error. We can utilize the following two techniques to overcome this:
- While initializing it, as described above, assign the value to a character array.
-
The value we want to add to the character array can be copied using the strcpy() function. The following is the strcpy() syntax:
strcpy(char destination, const char source);
The string pointed by the source is copied to the destination, along with the null character. For instance:char str[20];
strcpy(str,"Strings.");
This gives the string its assigned value.
Note – Making sure the value assigned has a length that is less than or equal to the character array’s maximum size.
Highlights:
- Once they have been declared, character arrays cannot be given a string literal using the ‘=’ operator.
- Both initialization time and the strcpy() function can be used for assignment.
Read String from the User
Scanf(), the most popular method for reading strings, reads a string of characters until it runs into whitespace (i.e., space, newline, tab, etc.). The process of accepting input with whitespace is described in the section that follows. For instance,
char str[25];
scanf("%s", str);
If we enter the following input:
PrepBytes is amazing.
We obtain the following Output:
PrepBytes
As we can see, once it detects whitespace, scanf() stops accepting input.
Note –
- In C, %s is the format specifier that is used to input and output strings.
- You may have noticed that the variable’s name is typically prefixed by a & operator when using scanf(). This is not the case in this instance since the character array’s character pointer points to the address of the array’s first character. Therefore, there is no need to employ the address operator(&).
Highlights: In C, scanf() can be used to read strings. But it only reads till it hits a whitespace.
How to Read a Line of Text?
As it automatically stops reading when it encounters whitespace, the scanf() operation cannot read strings that contain spaces. By combining fgets() with puts(), we can read and print strings with whitespace:
- fgets() An array of characters can be read using the fgets() method. Its statement is as follows:
fgets(name_of_string, number_of_characters, stdin);
*name_of_string: It is the variable where the string will be kept. number_of_characters: You should read the string’s maximum length. stdin:** The string needs to be read from the filehandle in this case. - puts(): The function puts() makes it easy to show strings.
puts(name_of_string);
name_of_string: It is the variable that will hold the string.
Using both functions as an example:
#include <stdlib.h> #include <stdio.h> int main() { char str[30]; printf("Enter string: "); fgets(str, sizeof(str), stdin); printf("The string is: "); puts(str); return 0; }
Input
Learn Coding From PrepBytes
Output
The string is: Learn Coding From PrepBytes
The strength of fgets() and puts() is shown in the above example, where we can see that the entire string, including the whitespace, was stored and printed.
Highlights:
- To solve the issue of reading a line of text with whitespace, fgets() and puts() are combined.
- Syntax for fgets():
fgets(name_of_string, number_of_characters, stdin); - Syntax for puts():
puts(name_of_string);
Passing Strings to Functions
Strings can be passed to functions in the same way that we give an array to a function, whether as an array or as a pointer, since they are just character arrays. Let’s examine this using the following program:
#include <stdio.h> void pointer(char * str) { printf("The string is : "); puts(str); printf("\n"); } void array(char str[]) { printf("The string is : "); puts(str); printf("\n"); } int main() { char str[25] = "PrepBytes is amazing."; pointer(str); array(str); return 0; }
Output
The string is : PrepBytes is amazing.
The string is : PrepBytes is amazing.
As we can see, both of them yield the same Output.
Highlights: Functions may accept a string as a character array or even as a pointer.
Strings and Pointers
As we’ve seen, character arrays that function as pointers are used in C to represent strings. As a result, we can manipulate or even perform operations on the string using pointers.
#include <stdlib.h> #include <stdio.h> int main() { char str[] = "PrepBytess."; printf("%c", *str); // Output: P printf("%c", *(str + 1)); // Output: r printf("%c\n", *(str + 6)); // Output: t char * stringPtr; stringPtr = str; printf("%c", *stringPtr); // Output: P printf("%c", *(stringPtr + 1)); // Output: r printf("%c", *(stringPtr + 6)); // Output: t return 0; }
Output
Prt
Prt
Note: We can easily manipulate strings using pointers since character arrays behave like points.
C String Example
This program illustrates everything we learnt in this article, so check it out:
#include <stdio.h> void array(char str[]) { printf("This function handles string literals with character arrays.\n"); printf("First character : %c\n", str[0]); printf("The entire string is : %s\n", str); str[0] = 'Q'; //Here we have assigned the first element of the array to Q. printf("The new string is : %s\n", str); } void literal(char * str) { printf("This function handles string literals using pointers.\n"); printf("First character : %c\n", str[0]); printf("The entire string is : %s\n", str); // str[0] = 'Q'; //Modification is not possible with string literals, since they are stored on the read-only memory. } int main() { char str[] = "Strings."; //Here we have assigned the string literal to a character array. array(str); printf("\n"); char * strPtr = "Strings."; ////Here we have assigned the string literal to a pointer. literal(strPtr); return 0; }
Output
This function handles string literals with character arrays.
First character : S
The entire string is : Strings.
The new string is : Qtrings.
This function handles string literals using pointers.
First character : S
The entire string is : Strings.
Difference Between Character Array and String Literal
Let’s review string literals before moving on to the distinction. A group of zero or more multibyte characters surrounded in double quotes, such as "xyz," constitutes a string literal. String literals cannot be changed (and are placed in read-only memory). They behave in an ill-defined manner when you try to change their values.
Arrays can be initialized using string literals. This has been demonstrated numerous times in the article. Let’s examine the differences now using the examples below:
1. char str[] = "PREPBYTES.";
With this command, a character array that has a string literal attached to it is created. It operates like a typical array and allows for modification and other common operations. The only thing to keep in mind is that even though we only initialized 11 members, the size of the array is actually 12, since the compiler added the \0 at the end.
*2. char str = "PREPBYTES.";**
The above statement generates a pointer that points to the string literal, specifically to the string literal’s first character. Now that we are aware that string literals are kept in a read-only memory region, we may conclude that modification is not allowed.
Note – It is defined to declare string literals as constants when printing them, such as:
const char *str = "Strings.";
This avoids the warning that appears when printf() is used with string literals.
Highlights:
- Most compilers store string literals in their read-only memory section. As a result, they cannot be changed.
- We can modify character arrays as well as conduct other common operations on arrays.
- Just like string literals, pointers that point to them cannot be changed.
Conclusion
In this article, we have tried to cover C strings and how to declare strings in C in various ways. Just go through this article completely, you will surely get the idea of what is a string in C and how to declare a string in C. Practicing string makes your coding skills stronger every day.
Frequently Asked Questions (FAQs)
Q1. What is the definition of a C string?
In C, a string is a group of characters arranged in a linear fashion. It is implemented using character arrays or pointers to string literals. Strings are terminated with a null character (‘\0’).
Q2. How can I declare a string in C?
In C, strings are declared using character arrays. The general syntax for declaring a string is char variableName[arraySize];
. For example, char str[50];
declares a string variable named "str" with a maximum size of 50 characters.
Q3. What are the different ways to initialize strings in C?
There are several ways to initialize strings in C:
Assigning a string literal with a size: char str[8] = "PrepBytes.";
Assigning a string literal without a size: char str[] = "PREPBYTES";
Assigning character by character with a size: char str[11] = {'P', 'R', 'E', 'P', 'B', 'Y', 'T', 'E', 'S', '.', '\0'};
Assigning character by character without a size: char str[] = {'P', 'R', 'E', 'P', 'B', 'Y', 'T', 'E', 'S', '.', '\0'};
Q4. How can I read a string from the user in C?
To read a string from the user in C, you can use the scanf()
function with the %s
format specifier. For example, scanf("%s", str);
will read a string of characters until it encounters whitespace.
Q5. Can strings be passed to functions in C?
Yes, strings can be passed to functions in C. Since strings are represented as character arrays or pointers, they can be passed as arguments to functions just like any other array. Functions can accept strings as character arrays or pointers.