Declaration
In C programming, defining a string is as simple as declaring a one-dimensional array of characters of a specific type. Below is the syntax for declaring a string.
char string_name[size];
In the provided syntax,
- string_name: This signifies the identifier given to the string variable.
- size: Its purpose is to specify the size of the string, indicating the number of characters it can contain.
There are two methods to define a string in the C programming language:
- Using a character array
- Using a string literal
Using char array
Let's explore an example of initializing a string using a character array in the C programming language.
char ch[10]={'t', 'p', 'o', 'i', 'n', 't', 't', 'e', 'c', 'h', '\0'};
As it is common knowledge, array indexing commences from 0, therefore it is depicted as shown in the figure below.
When declaring a string, specifying the size is optional. Therefore, the code above can be modified as shown below:
char ch[]={'t', 'p', 'o', 'i', 'n', 't', 't', 'e', 'c', 'h', '\0'};
Using string literal
We can also specify a string using a string literal in the C programming language. For instance:
char ch[]="logic practice";
In this scenario, the compiler will add '\0' at the end of the string.
Initialization
We have the option to set up a string by either utilizing a collection of characters or a string constant.
C String Example
Let's explore a basic example to demonstrate string manipulation in the C programming language.
Example
#include<stdio.h>
#include <string.h>
int main(){ //main function
char ch[11]={ 't', 'p', 'o', 'i', 'n', 't', 't', 'e', 'c', 'h', '\0'};
char ch2[11]="logic practice";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch2);
return 0;
}
Output:
Char Array Value is: logic practice
String Literal Value is: logic practice
Explanation:
In this illustration, we showcase a pair of methods for initializing and displaying character arrays (strings) in the C programming language. Subsequently, the array ch is set up by specifying individual characters, including the null terminator '\0', while ch2 is initialized with a string literal. Both arrays are then printed using the %s format specifier, resulting in the identical output: "logic practice".
Accessing Elements
In the C programming language, individual characters within a string can be accessed by specifying their position, much like working with an array. The character's position is denoted by an index enclosed in square brackets following the string variable name.
C String Example to Accessing Elements
Let's consider a scenario to demonstrate the process of accessing elements in a C String.
Example
#include <stdio.h>
int main() { //main function
char string[] = "Logic Practice";
printf("%c\n", string[5]);
printf("%c\n", string[8]);
printf("%c", string[10]);
return 0;
}
Output:
Explanation:
In this instance, we create a character array containing the phrase "Logic Practice" and display specific characters by their positions. Since arrays in C start at index zero, string[5] corresponds to the sixth character 't', and string[8] corresponds to the ninth character 'c'. These characters are then printed on separate lines. When we access string[10], it retrieves the null terminator '\0', indicating the string's end without displaying any visible output. Therefore, the output consists of 't' and 'c', each on its own line.
Updating Elements
In C programming, there is a capability to modify a character within a string. This functionality permits the alteration of any character within a string by referencing the index of that specific character.
C String Example to Update Elements
Let's consider an instance to demonstrate the process of modifying elements in C Strings.
Example
#include <stdio.h>
int main() { //main function
char string[] = "Logic PracticeTech";
printf("Before updating of string: %s \n",string);
string[0]='t';
string[1]='p';
string[6]='t';
printf("After updating the string: %s\n", string);
return 0;
}
Output:
Before updating of string: Logic PracticeTech
After updating the string: logic practice
Explanation:
In this instance, we initialize a character array using the string "Logic PracticeTech" and then proceed to display it. Subsequently, the program alters specific elements in the array: string[0] becomes 't', string[1] becomes 'p', and string[6] becomes 't'. After these modifications, the updated string is printed. Consequently, the result will exhibit the initial string first, succeeded by the adjusted string "logic practice".
String Length
In the C programming language, it is necessary to iterate through the string until reaching the null character ('\0') in order to calculate the string's length. The strlen function provided by the C standard library is commonly employed for this purpose.
C String Example to String length
Let's consider an example to determine the length of a string in C programming.
Example
#include <stdio.h>
#include <string.h>
int main() { //main function
char string[] = "Logic Practice";
int a=strlen(string);
printf("Length of the string is: %d\n", a);
return 0;
}
Output:
Length of the string is: 10
Explanation:
In this instance, we define a character array containing the text "Logic Practice" and determine its size by employing the strlen function from the string.h header file, which provides the character count. Subsequently, the program displays the length, which is 10.
Traversing String
In C programming, navigating through strings is a fundamental skill that plays a crucial role across various programming languages. Manipulating extensive text data often requires string traversal, which involves moving through the characters within the text. String traversal differs from traversing an array of integers in that while the length of the integer array must be known beforehand, in the case of strings, we can utilize the null character to signify the end of the string and effectively conclude the traversal process.
Therefore, there are two methods to iterate through a string.
- One method involves utilizing the string length.
- Another method involves utilizing the null character.
Let's discuss each one of them.
Using the length of string
Let's explore a demonstration of calculating the quantity of vowels in a given string.
Example
#include<stdio.h>
int main ()
{
char s[11] = "logic practice";
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 4
Using the null character
Let's explore the identical scenario of tallying the quantity of vowels using the null terminator.
Example
#include<stdio.h>
int main ()
{
char s[11] = "logic practice";
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 4
Accepting string as the input
In C programming, the scanf function is commonly utilized for user input. It can also be employed for string input, albeit with a specific approach. Take a look at the following code snippet that captures a string until a space character is encountered.
C Example to Accept String as the Input
Let's consider an example to demonstrate accepting strings as input in the C programming language.
Example
#include<stdio.h>
#include<string.h>
int main ()
{
char s[20];
printf("Enter the string: ");
scanf("%s",s);
printf("You entered %s",s);
}
Output:
Enter the string: Hello Logic Practice
You entered Hello
It is evident that the provided code is not suitable for handling space-separated strings. To enable the code to process such strings correctly, a slight modification is needed in the scanf function. Specifically, instead of using scanf("%s",s), the appropriate syntax would be: scanf("%[^\n]s",s). This adjustment directs the compiler to store the string s until a new line (\n) character is detected. Let's explore a sample scenario to store strings with spaces between them.
Example
#include<stdio.h>
int main ()
{
char s[20];
printf("Enter the string: ");
scanf("%[^\n]s",s);
printf("You entered %s",s);
}
Output:
Enter the string: Hello Logic Practice
You entered Hello Logic Practice
Explanation:
Here, it is important to recognize that the address of the string is already implied when working with arrays of characters. Since the array name represents the base address of the string, there is no requirement to explicitly use the address-of (&) operator with scanf for storing a string.
Using fgets
If we need to capture an entire string, including spaces, we should utilize the fgets function. Unlike scanf, fgets reads the complete line, spaces included, until it encounters a newline character.
C String Example using fgets
Let's consider an example to demonstrate the fgets function with C strings.
Example
#include <stdio.h>
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("You entered: %s", str);
return 0;
}
Output:
Enter a string: Logic Practice
You entered: Logic Practice
Explanation:
In this instance, we utilize the fgets function to capture the complete line of user input, encompassing spaces, and store it in a character array named str. The process prompts the user to enter a string, securely stores up to 99 characters, and subsequently displays the inputted string. Using fgets is recommended over scanf("%s", ...) due to its capability to read spaces and prevent buffer overflow. Should there be adequate space in the buffer, the input may incorporate a newline character.
Some importanLogic Practices
However, it is crucial to pay attention to the following considerations when inputting strings using scanf.
- The compiler does not conduct bounds checking on the character array. Consequently, there is a possibility that the string's length might surpass the character array's size, potentially leading to the overwriting of critical data.
- An alternative to scanf is gets, a built-in function specified in the string.h header file. Unlike scanf, gets is designed to accept one string per operation.
Using puts and fputs Functions
In C programming, we commonly utilize the printf function along with the %s specifier to showcase a string. As substitutes, we may opt for the puts function (which has been deprecated in C11 and C17 versions) or the fputs function.
Example
#include <stdio.h>
int main() {
char str[] = "Hello from Logic Practice!";
puts("Using puts():");
puts(str);
printf("Using fputs():\n");
fputs(str, stdout);
return 0;
}
Output:
Using puts():
Hello from Logic Practice!
Using fputs():
Hello from Logic Practice!
Explanation:
In this instance, we declare a string and display it using the puts and fputs functions. Initially, puts("Using puts:") showcases a heading, followed by puts(str) displaying the string and automatically appending a line break. Subsequently, printf("Using fputs:\n") demonstrates another heading with a line break. Lastly, fputs(str, stdout) showcases the string without adding a line break after printing, unlike puts.
Passing Strings to Function
Since strings are essentially arrays, we can treat them like arrays when passing them as arguments to functions.
C Example to Pass Strings to Functions
Let's consider a scenario to demonstrate the process of passing strings to functions in the C programming language.
Example
#include <stdio.h>
void displayString(char str[]) {
printf("The string is: %s\n", str);
}
int main() {
char message[] = "Hello from main!";
displayString(message);
return 0;
}
Output:
The string is: Hello from main!
Explanation:
In this instance, we define a string within the main function and pass it to a separate function named displayString. Subsequently, the displayString function receives the string as a parameter in the form of a character array and showcases its content. This demonstration illustrates the process of passing strings to functions in the C programming language by simply providing the array name, which inherently acts as a pointer to the initial character of the string.
Pointers with Strings
In C, we have employed pointers with arrays, functions, and primitive data types thus far. Nevertheless, pointers can also be utilized to reference strings. There are multiple benefits to utilizing pointers to reference strings. Let's examine the subsequent example to access the string through the pointer.
C Example to Pointers with Strings
Let's consider an example to demonstrate pointers with strings in C programming.
Example
#include<stdio.h>
int main ()
{
char s[11] = "logic practice";
char *p = s; // pointer p is pointing to string s.
printf("%s",p); // the string logic practice is printed if we print p.
}
Output:
logic practice
[Program Output]
As it is common knowledge that a string represents a sequence of characters, pointers can be applied in a similar manner as they are with arrays. In the given illustration, p is defined as a pointer pointing to the character array s. Pointer p behaves analogously to s, as s serves as the starting address of the string and is internally treated as a pointer. Nevertheless, modifying the contents of s or duplicating s directly is not feasible. To achieve this objective, pointers are essential for storing strings. Below, we demonstrate the utilization of pointers for replicating the contents of one string into another.
Example
#include<stdio.h>
int main ()
{
char *p = "hello logic practice";
printf("String p: %s\n",p);
char *q;
printf("copying the content of p into q...\n");
q = p;
printf("String q: %s\n",q);
}
Output:
String p: hello logic practice
copying the content of p into q...
String q: hello logic practice
Once a string is declared, it is immutable and cannot be assigned a new sequence of characters. Nonetheless, by utilizing pointers, we have the ability to assign a sequence of characters to the string. Let's examine the illustration below.
Example
#include<stdio.h>
void main ()
{
char *p = "hello logic practice";
printf("Before assigning: %s\n",p);
p = "hello";
printf("After assigning: %s\n",p);
}
Output:
Before assigning: hello logic practice
After assigning: hello
C Strings MCQs
1) What is the purpose of the null character '\0' in C strings?
- To mark the start of the string
- To separate words in a string
- To indicate the end of the string
- To count characters in a string
2) Which of the following correctly initializes a string using a string literal?
- char s = "tech";
- char s = {'t','e','c','h'};
- char s[5] = tech;
- string s = "tech";
3) Which function is used to determine the length of a string in C?
- strlength
- length
- strlen
- getlen
4) What will the output of the following code?
char str[] = "hello";
printf("%c", str[1]);
5) What is the main difference between puts and fputs functions?
- puts reads input, fputs writes output
- There is no difference
- puts works with files, fputs does not
- puts appends newline automatically, fputs does not