In C, a string is an array of characters that ends with a null character (\0). String functions are used to manipulate strings, such as copying, concatenating, comparing, and searching.
Declare a String
char str[SIZE];
where SIZE is the maximum number of characters that can be stored in the string.
Initialize a String
char str[] = "Hello World";
or
char str[SIZE] = "Hello World";
Access individual Characters in a String
char c = str[index];
where index is the position of the character in the string, starting from 0.
Some common string functions that can be used in C are:
- strcpy(dest, src): Used for copying one string to another.
- strcat(dest, src): Used for concatenating two strings.
- strlen(str): Used for finding the length of a string.
- strcmp(str1, str2): Used for comparing two strings.
Example:
#include <stdio.h> #include <string.h> int main() { char str1[20] = "Hello"; char str2[20] = "World"; char str3[20]; // Copying string str1 to str3 strcpy(str3, str1); printf("str3 after strcpy(): %s\n", str3); // Concatenating string str1 and str2 strcat(str1, str2); printf("str1 after strcat(): %s\n", str1); // Finding the length of string str1 int len = strlen(str1); printf("Length of str1: %d\n", len); // Comparing string str1 and str2 int cmp = strcmp(str1, str2); printf("Result of strcmp(): %d\n", cmp); return 0; }
This program will display the following output:
str3 after strcpy(): Hello str1 after strcat(): HelloWorld Length of str1: 10 Result of strcmp(): 1
String functions are an important tool for processing and manipulating text in a program. They can be used to implement string algorithms, parsing, and formatting, among other things.