In C, string functions are part of the standard library (string.h) and are used for performing various operations on strings. Here are some common types of string functions along with their syntax and examples:
-
String Copy (strcpy):
Syntax:
char *strcpy(char *destination, const char *source);
Description:
Copies the contents of the source string to the destination string.
Example:
#include <stdio.h>
#include <string.h>int main() {
char source[] = “Hello, World!”;
char destination[20];strcpy(destination, source);
printf(“Copied string: %sn”, destination);
return 0;
}
-
String Concatenation (strcat):
Syntax:
char *strcat(char *destination, const char *source);
Description:
Concatenates the source string to the end of the destination string.
Example:
#include <stdio.h>
#include <string.h>int main() {
char str1[20] = “Hello”;
char str2[] = “, World!”;strcat(str1, str2);
printf(“Concatenated string: %sn”, str1);
return 0;
}
-
String Length (strlen):
Syntax:
size_t strlen(const char *str);
Description:
Returns the length of the input string str, excluding the null character.
Example:
#include <stdio.h>
#include <string.h>int main() {
char str[] = “Hello, World!”;size_t length = strlen(str);
printf(“Length of the string: %lun”, length);
return 0;
}
-
String Comparison (strcmp):
Syntax:
int strcmp(const char *str1, const char *str2);
Description:
Compares two strings (str1 and str2). Returns 0 if the strings are equal, a positive value if str1 is greater, and a negative value if str2 is greater.
Example:
#include <stdio.h>
#include <string.h>int main() {
char str1[] = “apple”;
char str2[] = “orange”;int result = strcmp(str1, str2);
if (result == 0) {
printf(“Both strings are equal.n”);
} else if (result < 0) {
printf(“%s comes before %s.n”, str1, str2);
} else {
printf(“%s comes after %s.n”, str1, str2);
}return 0;
}
These are just a few examples of the many string functions available in the C standard library. Each function serves a specific purpose and can be used to manipulate and process strings efficiently.