String Functions in C
0 226
String functions in C are tools provided by the language to work with character arrays, commonly known as strings.
These functions enable various operations like copying strings, concatenating them, finding their lengths, comparing them, and searching for specific characters or substrings.
They are crucial for manipulating and analyzing textual data efficiently in C programming. Examples include functions like strlen(), strcpy(), strcat(), strcmp(), and strstr(). Understanding and utilizing these functions effectively is essential for proficient C programming.
1strlen() - String Length: This function calculates the length of a string, i.e., the number of characters in the string excluding the null terminator ('\0').
2strcpy() - String Copy: This function copies the contents of one string to another.
3strcat() - String Concatenation: This function appends the content of one string to the end of another.
4strcmp() - String Comparison: This function compares two strings lexicographically.
5strstr() - Substring Search: This function searches for the first occurrence of a substring within another string.
Example:
// Program for string Functions in C
#include<stdio.h>
#include<string.h>
int main() {
char str1[50] = "Hello";
char str2[50] = "World!";
char str3[50];
// strlen() - String Length
printf("Length of str1: %d\n", (int)strlen(str1));
// strcpy() - String Copy
strcpy(str3, str1);
printf("Copied string: %s\n", str3);
// strcat() - String Concatenation
strcat(str1, " ");
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
// strcmp() - String Comparison
int cmp = strcmp(str1, str2);
if (cmp == 0)
printf("str1 is equal to str2\n");
else if (cmp < 0)
printf("str1 is less than str2\n");
else
printf("str1 is greater than str2\n");
// strchr() - Find Character in String
char *ptr = strchr(str1, 'o');
if (ptr != NULL)
printf("1st occurrence of 'o' in str1 at index: %ld\n", ptr - str1);
else
printf("Character 'o' not found in str1\n");
// strstr() - Find Substring in String
ptr = strstr(str1, "World");
if (ptr != NULL)
printf("Substring 'World' found in str1 at index: %ld\n", ptr - str1);
else
printf("Substring 'World' not found in str1\n");
return 0;
}
Output:
Length of str1: 5
Copied string: Hello
Concatenated string: Hello World!
str1 is less than str2
1st occurrence of 'o' in str1 at index: 4
Substring 'World' found in str1 at index: 6
Share:
Comments
Waiting for your comments