In C Language, strings are sequences of characters terminated by a null character ('\0').
C does not have a built-in string data type like other programming languages.
Instead, strings are typically represented as arrays of characters.
#include <stdio.h> int main() { // Declaring and initializing a string using an array of characters char str1[] = "Hello, World!"; // Declaring a string without initialization char str2[20]; // Maximum length of 20 characters // Initializing a string later str2[0] = 'H'; str2[1] = 'i'; str2[2] = '\0'; // Null terminator printf("str1: %s\n", str1); printf("str2: %s\n", str2); return 0; }
#include <stdio.h> int main() { char str[50]; // Maximum length of 50 characters printf("Enter your name: "); scanf("%s", str); printf("You entered: %s\n", str); return 0; }
C provides several standard library functions for working with strings, such as:
Calculates the length of a string.
Output: Length of str: 13
#include <stdio.h> #include <string.h> int main() { char str[] = "Hello, World!"; int length = strlen(str); printf("Length of str: %d\n", length); return 0; }
#include <stdio.h> #include <string.h> int main() { char src[] = "Hello, C!"; char dest[20]; strcpy(dest, src); printf("Copied string: %s\n", dest); return 0; }
Output: Copied string: Hello, C!
#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!
#include <stdio.h> #include <string.h> int main() { char str1[] = "Hello, C"; char str2[] = "Hello, C"; if (strcmp(str1, str2) == 0) { printf("Strings are equal.\n"); } else { printf("Strings are not equal.\n"); } return 0; }
#include <stdio.h> #include <string.h> int main() { char str[] = "Hello,World,How,Are,You"; char *token = strtok(str, ","); while (token != NULL) { printf("%s\n", token); token = strtok(NULL, ","); } return 0; }
Output: Strings are equal.
#include <stdio.h> #include <string.h> int main() { char str[] = "Hello, World!"; char *substr = strstr(str, "World"); printf("Substring: %s\n", substr); return 0; }
Output: >Hello >World >How >Are >You
#include <stdio.h> #include <string.h> int main() { char str[] = "Hello"; printf("Original string: %s\n", str); printf("Reversed string: %s\n", strrev(str)); return 0; }
Output: Substring: World!
Output: Original string: Hello Reversed string: olleH
Copies a string.
Concatenates two strings.
Compares two strings.
Splits a string into tokens.
Locates a substring within a string.
Reverses a string.