Strings in C Programming
Hello Everyone, In this article, we will cover the concept of Strings in C Programming. You will learn what strings are, how to create and manipulate them, and understand the functions and techniques used to work with strings effectively. Whether you are new to C or have some experience, this guide will help you to understand basics of Strings in C effectively with examples. Let’s get started.
In C programming, a string is a sequence of characters terminated by a null character (‘\0’). It’s essentially an array of characters with the last element being the null character, which indicates the end of the string. Strings are often used to store and manipulate text data in C programs.
Example of how to declare and initialize a string in C:
#include <stdio.h>
int main() {
// Declare and initialize a string using an array of characters
char greeting[] = {'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\\0'};
// Print the string
printf("%s\\n", greeting);
// Declare and initialize a string using a string literal
char name[] = "John Doe";
// Print the string
printf("%s\\n", name);
return 0;
}
In this example, we declare and initialize two strings: greeting and name. The greeting string is initialized using an array of characters, while the name string is initialized using a string literal. Both strings are terminated by a null character (‘\0’). The printf function is used to print the strings to the console.
In C language, there are two common ways to declare a string:
1. Character Array: You can declare a string by defining a character array with a specified size. The size should be large enough to hold the characters and the null character (‘\0’) that terminates the string.
char string_name[size];
For example:
char my_string[20];
2. Pointer to a Character: You can also declare a string by defining a pointer to a character. This method uses dynamically allocated memory for the string, and you don’t need to specify the size upfront. However, you should ensure that enough memory is allocated to hold the characters and the null character (‘\0’).
char *string_name;
For example:
char *my_string;
It’s important to note that if you use a pointer to a character, you need to allocate memory for the string before using it. This can be done using memory allocation functions like malloc or calloc.
Here’s an example demonstrating both ways to declare a string:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// Declare a string using a character array
char string_array[20] = "Hello, World!";
// Print the string
printf("String using character array: %s\\n", string_array);
// Declare a string using a pointer to a character
char *string_pointer;
// Allocate memory for the string and copy the content
string_pointer = (char *) malloc(strlen("Hello, World!") + 1);
strcpy(string_pointer, "Hello, World!");
// Print the string
printf("String using pointer to a character: %s\\n", string_pointer);
// Free the allocated memory
free(string_pointer);
return 0;
}
Continuing from the previous example, let’s explore some more operations and functions that can be performed on strings in C language.
String Length: You can find the length of a string (excluding the null character) using the strlen()
function from the string.h
library.
#include <string.h>
int length = strlen(string_name);
String Concatenation: To join two strings together, you can use the strcat()
function from the string.h
library. This function appends the second string to the first string.
#include <string.h>
strcat(string1, string2);
String Comparison: To compare two strings, you can use the strcmp()
function from the string.h
library. This function returns 0 if the strings are equal, a positive value if the first string is greater, and a negative value if the first string is smaller (in lexicographic order).
#include <string.h>
int result = strcmp(string1, string2);
Here’s an example demonstrating these operations:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// Declare and initialize two strings
char string1[20] = "Hello, ";
char string2[] = "World!";
// Find the length of the strings
int length1 = strlen(string1);
int length2 = strlen(string2);
// Print the length of the strings
printf("Length of string1: %d\\n", length1);
printf("Length of string2: %d\\n", length2);
// Concatenate the strings
strcat(string1, string2);
// Print the concatenated string
printf("Concatenated string: %s\\n", string1);
// Compare the strings
int result = strcmp(string1, string2);
// Print the result of the comparison
if (result == 0) {
printf("Strings are equal\\n");
} else if (result > 0) {
printf("String1 is greater\\n");
} else {
printf("String1 is smaller\\n");
}
return 0;
}
In this example, we declare and initialize two strings, string1 and string2. We find their lengths using strlen(), concatenate them using strcat(), and compare them using strcmp(). The result of the comparison and other operations is printed to the console.
In this example, we’ll declare and initialize a string with the word “UTOPPER” using individual characters, and then print the string:
#include <stdio.h>int main() {
// Declare and initialize a string with the word "UTOPPER" using individual characters
char word[] = {'U', 'T', 'O', 'P', 'P', 'E', 'R', '\\0'};
// Print the string
printf("The word is: %s\\n", word);
return 0;
}
In this example, we declare a character array named word and initialize it using individual characters from the word “UTOPPER”, followed by the null character (‘\0’) to indicate the end of the string. The printf function is used to print the string to the console.
What is Traversing String
Traversing a string means going through each character in the string one by one, typically using a loop. This is a common operation when working with strings in C programming, as it allows you to perform various tasks such as counting characters, finding specific characters, or modifying the string.
Here’s an example that demonstrates traversing a string in C using a for loop:
#include <stdio.h>
#include <string.h>
int main() {
// Declare and initialize a string
char my_string[] = "Traversing a string in C";
// Find the length of the string
int length = strlen(my_string);
// Traverse the string using a for loop
for (int i = 0; i < length; i++) {
// Access the character at position i
char current_char = my_string[i];
// Print the character and its position in the string
printf("Character at position %d: %c\\n", i, current_char);
}
return 0;
}
In this example, we first declare and initialize a string named my_string. Then, we find the length of the string using the strlen() function from the string.h library. We use a for loop to traverse the string, going through each character one by one, and print the character and its position in the string.
Alternatively, you can traverse a string using a while loop and a pointer:
#include <stdio.h>
int main() {
// Declare and initialize a string
char my_string[] = "Traversing a string in C";
// Declare a pointer to traverse the string
char *ptr = my_string;
// Traverse the string using a while loop and a pointer
int position = 0;
while (*ptr != '\\0') {
// Print the character and its position in the string
printf("Character at position %d: %c\\n", position, *ptr);
// Move the pointer to the next character
ptr++;
position++;
}
return 0;
}
In this alternative example, we use a while loop and a pointer named ptr to traverse the string. The loop continues until the pointer reaches the null character (‘\0’), indicating the end of the string. In each iteration, we print the character and its position in the string, and then move the pointer to the next character.
Output
Character at position 0: T
Character at position 1: r
Character at position 2: a
Character at position 3: v
Character at position 4: e
Character at position 5: r
Character at position 6: s
Character at position 7: i
Character at position 8: n
Character at position 9: g
Character at position 10:
Character at position 11: a
Character at position 12:
Character at position 13: s
Character at position 14: t
Character at position 15: r
Character at position 16: i
Character at position 17: n
Character at position 18: g
Character at position 19:
Character at position 20: i
Character at position 21: n
Character at position 22:
Character at position 23: C
Here are three different C programs that count the number of vowels in a string. Each program accepts a string as input and counts the vowels using different methods: a for
loop, a while
loop with null character, and a while
loop with gets()
function.
1. Using a for loop:
#include <stdio.h>
#include <string.h>
int is_vowel(char ch) {
ch = tolower(ch);
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
}
int main() {
char str[100];
int count = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
int length = strlen(str);
for (int i = 0; i < length; i++) {
if (is_vowel(str[i])) {
count++;
}
}
printf("Number of vowels: %d\\n", count);
return 0;
}
2. Using a while loop with null character:
#include <stdio.h>
#include <ctype.h>
int is_vowel(char ch) {
ch = tolower(ch);
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
}
int main() {
char str[100];
int count = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
int i = 0;
while (str[i] != '\\0') {
if (is_vowel(str[i])) {
count++;
}
i++;
}
printf("Number of vowels: %d\\n", count);
return 0;
}
3. Using a while loop with gets() function:
#include <stdio.h>
#include <ctype.h>
int is_vowel(char ch) {
ch = tolower(ch);
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
}
int main() {
char str[100];
int count = 0;
printf("Enter a string: ");
gets(str);
int i = 0;
while (str[i] != '\\0') {
if (is_vowel(str[i])) {
count++;
}
i++;
}
printf("Number of vowels: %d\\n", count);
return 0;
}
Please note that the gets() function is considered unsafe and deprecated, as it can cause buffer overflow. It’s better to use fgets() instead.
Here is a C program that counts the number of vowels in a string using the fgets()
function to accept the input string:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int is_vowel(char ch) {
ch = tolower(ch);
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
}
int main() {
char str[100];
int count = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
int length = strlen(str);
for (int i = 0; i < length; i++) {
if (is_vowel(str[i])) {
count++;
}
}
printf("Number of vowels: %d\\n", count);
return 0;
}
In this program, we first include the necessary header files: stdio.h
, string.h
, and ctype.h
. The is_vowel()
function checks if a character is a vowel, considering both uppercase and lowercase characters.
The main() function uses the fgets() function to read the input string from the user. The fgets() function takes three parameters: the buffer to store the input string, the maximum number of characters to read (including the null character), and the input stream (stdin in this case).
After reading the input string, we loop through each character in the string and use the is_vowel() function to check if it is a vowel. If it is, we increment the count variable. Finally, we print the total number of vowels in the input string.
Write a c program that Accepting string as the input.
Here’s a simple C program that accepts a string as input using the fgets()
function and then prints the entered string:
#include <stdio.h>
int main() {
char input_string[100];
printf("Enter a string: ");
fgets(input_string, sizeof(input_string), stdin);
printf("You entered: %s", input_string);
return 0;
}
In this program, we first include the stdio.h
header file, which provides the necessary functions for input and output. We then declare a character array input_string
with a size of 100 to store the input string.
The fgets() function is used to read the input string from the user. It takes three parameters: the buffer to store the input string, the maximum number of characters to read (including the null character), and the input stream (stdin in this case). After reading the input string, we use the printf() function to print the entered string.
POINTER AS A STRING
A real-life analogy for pointers with strings in C programming can be thought of as a person reading a book. Imagine a book as a string of characters, and the person reading the book as the program. The person’s finger, pointing to a specific character in the book, acts like a pointer. As the person reads the book, they move their finger along the text, pointing to each character one by one. The person’s finger (the pointer) allows them to keep track of their position in the text (the string) and access the content (the characters).
Let’s break this analogy down in terms of C programming:
- The book is like a string: A sequence of characters.
- The person’s finger is like a pointer: Pointing to a specific character in the sequence.
- Reading the book is like traversing the string: The person moves their finger along the text, accessing each character in the sequence one by one.
Here’s a simple C program that demonstrates this analogy:
#include <stdio.h>
int main() {
// The book (string) containing a sentence
char sentence[] = "Reading a book is fun!";
// The person's finger (pointer) pointing to the first character of the sentence
char *finger = sentence;
// Reading the book (traversing the string)
printf("Characters in the sentence:\\n");
while (*finger != '\\0') {
printf("%c ", *finger);
finger++; // Move the finger (pointer) to the next character
}
printf("\\n");
return 0;
}
In this example, the sentence character array represents the book (the string), and the finger pointer represents the person’s finger pointing to a character in the book. The while loop demonstrates reading the book by traversing the string and printing each character in the sentence until the null character (‘\0’) is reached.
Pointers with strings in c programming
Pointers can be used with strings in C programming to access and manipulate the characters in the string more efficiently. Here’s an example of using pointers with strings:
#include <stdio.h>
int main() {
// Declare and initialize a string
char my_string[] = "Hello, World!";
// Declare a pointer to a character and initialize it with the address of the first character in the string
char *ptr = my_string;
// Print the string using the pointer
printf("The string is: %s\\n", ptr);
// Iterate through the string using the pointer
printf("The characters in the string are:\\n");
while (*ptr != '\\0') {
printf("%c ", *ptr);
ptr++;
}
printf("\\n");
return 0;
}
In this example, we first declare and initialize a string named my_string. We then declare a pointer to a character, named ptr, and initialize it with the address of the first character in the string (which is the same as just assigning it to my_string).
We use the printf() function to print the string using the pointer. Since the pointer points to the first character of the string, passing it as an argument to printf() with the %s format specifier will print the entire string.
To iterate through the string using the pointer, we use a while
loop. Inside the loop, we check if the current character pointed to by the pointer is not the null character (\\0
). If it’s not the null character, we print the character and then increment the pointer to point to the next character. The loop continues until the pointer reaches the null character, indicating the end of the string.
Output:
The string is: Hello, World!
The characters in the string are:
H e l l o , W o r l d !
The first line of the output is the entire string “Hello, World!” printed using the pointer. The second line displays the individual characters in the string, separated by spaces, as the pointer iterates through each character in the string.