C programming language provides several built-in functions in the standard library to manipulate strings. Here are some of the most commonly used string functions in C:
1. strlen(): This function returns the length of a string (not including the null character ‘\0’).
#include#include int main() { char str[] = "Hello, world!"; int len = strlen(str); printf("The length of the string is %d\n", len); return 0; }
2. strcpy(): This function copies the contents of one string to another string.
#include#include int main() { char str1[] = "Hello"; char str2[10]; strcpy(str2, str1); printf("str1: %s\n", str1); printf("str2: %s\n", str2); return 0; }
3. strcat(): This function concatenates two strings together.
#include#include int main() { char str1[] = "Hello"; char str2[] = ", world!"; strcat(str1, str2); printf("%s\n", str1); return 0; }
4. strcmp(): This function compares two strings and returns an integer value that indicates their relative order.
#include#include int main() { char str1[] = "apple"; char str2[] = "banana"; int result = strcmp(str1, str2); if (result < 0) { printf("%s comes before %s\n", str1, str2); } else if (result > 0) { printf("%s comes after %s\n", str1, str2); } else { printf("%s is the same as %s\n", str1, str2); } return 0; }
These are just a few examples of the many string functions available in C programming language. It is important to use these functions carefully to avoid buffer overflows and other errors when manipulating strings.