Operations on Strings in C
Understanding Operations on Strings
String operations involve various manipulations such as concatenation, reversal, and comparison.
We will explore three different methods to perform operations on strings in C.
Method 1: Using Standard Library Functions
This method uses built-in string functions for operations.
#include <stdio.h> #include <string.h> int main() { char str1[100] = "Hello"; char str2[] = " World"; strcat(str1, str2); printf("Concatenated String: %s\n", str1); printf("Length of String: %ld\n", strlen(str1)); return 0; }
Length of String: 11
Method 2: Using Character Array Manipulation
This method manually processes each character for operations.
#include <stdio.h> #include <string.h> void reverseString(char str[]) { int length = 0; while (str[length] != '\0') { length++; } for (int i = 0; i < length / 2; i++) { char temp = str[i]; str[i] = str[length - i - 1]; str[length - i - 1] = temp; } } int main() { char str[] = "Hello"; reverseString(str); printf("Reversed String: %s\n", str); return 0; }
Method 3: Using Pointer Manipulation
This method performs operations using pointers.
#include <stdio.h> #include <string.h> int compareStrings(char *str1, char *str2) { while (*str1 && *str2 && *str1 == *str2) { str1++; str2++; } return *str1 - *str2; } int main() { char str1[] = "Hello"; char str2[] = "Hello"; int result = compareStrings(str1, str2); if (result == 0) printf("Strings are equal\n"); else printf("Strings are not equal\n"); return 0; }