Strings in C (Character Arrays)
In C programming, strings are essentially arrays of characters. A string is a sequence of characters that is terminated by a special character called the null character ('\0'
). C does not have a built-in string data type like some other languages, so strings are typically represented as arrays of characters.
Let’s explore how strings (character arrays) work in C.
String Handling Functions in C
strlen(), strcpy() , strncpy(), strcat(),strncat(), strcmp(), strncmp(), strchr(), strrchr(),strstr(),strtok(), strdup(), strrev(), memset(), memcpy(), memmove(), memcmp()
What is a String?
A string in C is a sequence of characters stored in a character array, and it is always terminated by a null character ('\0'
). The null character marks the end of the string, allowing C to determine where the string ends in memory.
Example:
char name[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
In this example:
- The string
"Hello"
is stored in the arrayname
. - The size of the array is
6
, including the 5 characters of"Hello"
and the null terminator'\0'
.
Null Character:
The null character ('\0'
) is essential for marking the end of the string in C. It helps functions like printf
and strlen
determine where the string stops.
Declaring and Initializing Strings
You can declare and initialize strings in C in various ways.
1. Using Character Array with Explicit Size:
You can declare a character array with a fixed size and manually add a null character to terminate the string.
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
2. Using String Literals:
C allows you to use string literals (a sequence of characters enclosed in double quotes) to initialize character arrays. When using a string literal, the compiler automatically adds the null character.
char greeting[] = "Hello";
- The array
greeting
has enough space for all characters in"Hello"
plus the null terminator. - This is equivalent to the previous example but more convenient.
Accessing Characters in a String
Since strings are arrays, you can access individual characters using array indexing. The first character is at index 0
, and the last character (before the null terminator) is at index n-1
(where n
is the length of the string).
Example:
char name[] = "World";
printf("%c\n", name[0]); // Output: W
printf("%c\n", name[4]); // Output: d
Output:
W
d
You can also modify individual characters of a string since it is an array.
Example:
char name[] = "World";
name[0] = 'M';
printf("%s\n", name); // Output: Morld
Output:
Morld
String Handling Functions in C
- strlen() – Find the length of a string.
- strcpy() – Copy a string.
- strncpy() – Copy a specified number of characters from one string to another.
- strcat() – Concatenate two strings.
- strncat() – Concatenate a specified number of characters from one string to another.
- strcmp() – Compare two strings.
- strncmp() – Compare a specified number of characters from two strings.
- strchr() – Locate the first occurrence of a character in a string.
- strrchr() – Locate the last occurrence of a character in a string.
- strstr() – Locate a substring in a string.
- strtok() – Split a string into tokens.
- strdup() – Duplicate a string.
- strrev() – Reverse a string (non-standard function, supported in some C libraries).
- memset() – Fill a block of memory with a particular value.
- memcpy() – Copy a block of memory.
- memmove() – Move a block of memory.
- memcmp() – Compare two blocks of memory.
The C Standard Library provides several functions to handle and manipulate strings. These functions are declared in the <string.h>
header file. Here is a list of commonly used string handling functions:
Explanation of String Handling Functions with Syntax and Examples
1. strlen() – Find the Length of a String
The strlen()
function is used to calculate the length of a string, excluding the null character \0
.
- Syntax:
size_t strlen(const char *str);
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
int length = strlen(str);
printf("Length of the string is: %d\n", length);
return 0;
}
- Output:
Length of the string is: 13
2. strcpy() – Copy a String
The strcpy()
function copies a string from one location to another, including the null terminator \0
.
- Syntax:
char *strcpy(char *destination, const char *source);
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char destination[20];
strcpy(destination, source);
printf("Copied string: %s\n", destination);
return 0;
}
- Output:
Copied string: Hello, World!
3. strncpy() – Copy Specified Number of Characters
The strncpy()
function copies a specified number of characters from the source string to the destination string.
- Syntax:
char *strncpy(char *destination, const char *source, size_t num);
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char destination[20];
strncpy(destination, source, 5);
destination[5] = '\0'; // Manually add the null character
printf("Copied string: %s\n", destination);
return 0;
}
- Output:
Copied string: Hello
4. strcat() – Concatenate Two Strings
The strcat()
function appends the source string to the destination string.
- Syntax:
char *strcat(char *destination, const char *source);
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[] = ", World!";
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
- Output:
Concatenated string: Hello, World!
5. strncat() – Concatenate Specified Number of Characters
The strncat()
function concatenates a specified number of characters from the source string to the destination string.
- Syntax:
char *strncat(char *destination, const char *source, size_t num);
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[] = ", World!";
strncat(str1, str2, 3); // Concatenate only 3 characters from str2
printf("Concatenated string: %s\n", str1);
return 0;
}
- Output:
Concatenated string: Hello, Wo
6. strcmp() – Compare Two Strings
The strcmp()
function compares two strings lexicographically (character by character).
- Syntax:
int strcmp(const char *str1, const char *str2);
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
if (strcmp(str1, str2) == 0)
printf("Strings are equal\n");
else
printf("Strings are not equal\n");
return 0;
}
- Output:
Strings are not equal
7. strncmp() – Compare Specified Number of Characters
The strncmp()
function compares a specified number of characters from two strings.
- Syntax:
int strncmp(const char *str1, const char *str2, size_t num);
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "Helium";
if (strncmp(str1, str2, 3) == 0)
printf("First 3 characters are equal\n");
else
printf("First 3 characters are not equal\n");
return 0;
}
- Output:
First 3 characters are equal
8. strchr() – Locate First Occurrence of Character
The strchr()
function locates the first occurrence of a character in a string.
- Syntax:
char *strchr(const char *str, int character);
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *ptr = strchr(str, 'o');
if (ptr != NULL)
printf("First occurrence of 'o' found at position: %ld\n", ptr - str);
else
printf("'o' not found\n");
return 0;
}
- Output:
First occurrence of 'o' found at position: 4
9. strrchr() – Locate Last Occurrence of Character
The strrchr()
function locates the last occurrence of a character in a string.
- Syntax:
char *strrchr(const char *str, int character);
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *ptr = strrchr(str, 'o');
if (ptr != NULL)
printf("Last occurrence of 'o' found at position: %ld\n", ptr - str);
else
printf("'o' not found\n");
return 0;
}
- Output:
Last occurrence of 'o' found at position: 8
10. strstr() – Locate Substring in a String
The strstr()
function locates the first occurrence of a substring in a string.
- Syntax:
char *strstr(const char *haystack, const char *needle);
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *
ptr = strstr(str, "World");
if (ptr != NULL)
printf("Substring 'World' found at position: %ld\n", ptr - str);
else
printf("Substring 'World' not found\n");
return 0;
}
- Output:
Substring 'World' found at position: 7
11. strtok() – Split a String into Tokens
The strtok()
function splits a string into tokens based on a delimiter.
- Syntax:
char *strtok(char *str, const char *delimiters);
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World! Welcome to C programming.";
char *token = strtok(str, " ,!");
while (token != NULL) {
printf("Token: %s\n", token);
token = strtok(NULL, " ,!");
}
return 0;
}
- Output:
Token: Hello
Token: World
Token: Welcome
Token: to
Token: C
Token: programming
12. strdup() – Duplicate a String
The strdup()
function allocates memory and duplicates a string. It returns a pointer to the newly allocated copy of the string. This function is not part of the C standard but is available in many C libraries.
- Syntax:
char *strdup(const char *str);
- Example:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char original[] = "Hello, World!";
char *duplicate = strdup(original); // Duplicate the string
if (duplicate != NULL) {
printf("Original: %s\n", original);
printf("Duplicate: %s\n", duplicate);
free(duplicate); // Free the allocated memory
} else {
printf("Memory allocation failed.\n");
}
return 0;
}
- Output:
Original: Hello, World!
Duplicate: Hello, World!
13. strrev() – Reverse a String (Non-standard)
The strrev()
function reverses the characters of a string in place. This function is non-standard and may not be available in all C libraries.
- Syntax:
char *strrev(char *str);
- Example:
#include <stdio.h>
#include <string.h>
// A simple implementation of strrev for demonstration
char *strrev(char *str) {
int length = strlen(str);
for (int i = 0; i < length / 2; i++) {
char temp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = temp;
}
return str;
}
int main() {
char str[] = "Hello, World!";
printf("Original: %s\n", str);
printf("Reversed: %s\n", strrev(str));
return 0;
}
- Output:
Original: Hello, World!
Reversed: !dlroW ,olleH
14. memset() – Fill a Block of Memory with a Particular Value
The memset()
function sets all bytes in a block of memory to a particular value.
- Syntax:
void *memset(void *ptr, int value, size_t num);
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[50] = "Hello, World!";
memset(str, '-', 5); // Fill the first 5 characters with '-'
printf("Modified string: %s\n", str);
return 0;
}
- Output:
Modified string: -----, World!
15. memcpy() – Copy a Block of Memory
The memcpy()
function copies a specified number of bytes from the source memory block to the destination memory block. It’s often used for fast copying of large amounts of data.
- Syntax:
void *memcpy(void *destination, const void *source, size_t num);
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char destination[50];
memcpy(destination, source, strlen(source) + 1); // Copy the entire string including null terminator
printf("Copied string: %s\n", destination);
return 0;
}
- Output:
Copied string: Hello, World!
16. memmove() – Move a Block of Memory
The memmove()
function is similar to memcpy()
, but it is safer when the source and destination memory blocks overlap. It ensures that the source block is copied to a temporary location before moving to the destination, preventing data corruption.
- Syntax:
void *memmove(void *destination, const void *source, size_t num);
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
// Moving part of the string within the same array (overlapping regions)
memmove(str + 7, str, 5); // Move first 5 characters to index 7
printf("After memmove: %s\n", str);
return 0;
}
- Output:
After memmove: Hello, Hello!
17. memcmp() – Compare Two Blocks of Memory
The memcmp()
function compares the first num
bytes of two memory blocks and returns an integer indicating their relationship. It is typically used to compare binary data or strings stored in memory.
- Syntax:
int memcmp(const void *ptr1, const void *ptr2, size_t num);
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "Hellp"; // Slightly different from str1
int result = memcmp(str1, str2, 5);
if (result == 0) {
printf("The memory blocks are identical.\n");
} else if (result > 0) {
printf("str1 is greater than str2.\n");
} else {
printf("str1 is less than str2.\n");
}
return 0;
}
- Output:
str1 is less than str2.
Summary of String and Memory Handling Functions in C
Here’s a complete summary of all the string and memory handling functions discussed:
No | Function | Description | Example Output |
---|---|---|---|
1 | strlen() | Returns the length of a string (excluding the null character). | Length of the string is: 13 |
2 | strcpy() | Copies one string to another, including the null terminator. | Copied string: Hello, World! |
3 | strncpy() | Copies a specified number of characters from one string to another. | Copied string: Hello |
4 | strcat() | Concatenates two strings (appends source to destination). | Concatenated string: Hello, World! |
5 | strncat() | Concatenates a specified number of characters from one string to another. | Concatenated string: Hello, Wo |
6 | strcmp() | Compares two strings lexicographically. | Strings are not equal |
7 | strncmp() | Compares a specified number of characters from two strings. | First 3 characters are equal |
8 | strchr() | Finds the first occurrence of a character in a string. | First occurrence of ‘o’ found at position: 4 |
9 | strrchr() | Finds the last occurrence of a character in a string. | Last occurrence of ‘o’ found at position: 8 |
10 | strstr() | Finds the first occurrence of a substring in a string. | Substring ‘World’ found at position: 7 |
11 | strtok() | Splits a string into tokens based on a delimiter. | Token: Hello \n Token: World |
12 | strdup() | Duplicates a string and returns a pointer to the copy. | Original: Hello, World! \n Duplicate: Hello, World! |
13 | strrev() | Reverses a string in place (non-standard). | Original: Hello, World! \n Reversed: !dlroW ,olleH |
14 | memset() | Fills a block of memory with a specified value. | Modified string: —–, World! |
15 | memcpy() | Copies a block of memory from one location to another. | Copied string: Hello, World! |
16 | memmove() | Moves a block of memory (safe for overlapping regions). | After memmove: Hello, Hello! |
17 | memcmp() | Compares two blocks of memory byte by byte. | str1 is less than str2 |
Explanation of Key Functionality:
- String Manipulation:
- Basic Operations: Functions like
strlen()
,strcpy()
, andstrcat()
allow you to measure, copy, and concatenate strings. - Comparison: Functions like
strcmp()
andstrncmp()
let you compare strings lexicographically. - Searching: Functions like
strchr()
,strrchr()
, andstrstr()
help locate characters or substrings within a string.
- Memory Handling:
- Filling Memory: The
memset()
function is used to set all bytes in a block of memory to a specified value. - Copying Memory:
memcpy()
is a fast way to copy memory from one location to another, whilememmove()
ensures safe copying even when the source and destination overlap. - Comparing Memory: The
memcmp()
function compares two blocks of memory to determine whether they are identical or different.
- Special Operations:
- Tokenization:
strtok()
is useful for splitting a string into tokens based on delimiters. - Reversing and Duplicating Strings:
strrev()
reverses a string (though non-standard), andstrdup()
creates a duplicate of a string, dynamically allocating memory for the new copy.
These functions form the backbone of string and memory manipulation in C programming, providing essential tools for managing data efficiently. By mastering these functions, you can handle strings, copy memory, compare data, and perform various other operations that are critical in systems-level programming.