String Functions in C
When working with C programming, strings are an important aspect to understand and utilize. Strings, in the context of C programming, are an array of characters ending with a null character (\0
). In this article, we'll take a look at some of the most commonly used string functions in C that will help you to handle and manipulate strings more effectively.
strlen()
strlen()
is a function that returns the length of a given string. It doesn't count the null character \0
at the end of the string. Here's an example of how to use strlen()
:
#include <string.h>
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
printf("Length of the string is %lu\n", strlen(str));
return 0;
}
In the above code, strlen(str)
will return 13
, which is the length of the string "Hello, World!".
strcpy()
strcpy()
is a function that copies the string pointed by source (including the null character) to the destination. Here's an example of how to use strcpy()
:
#include <string.h>
#include <stdio.h>
int main() {
char source[] = "Hello, World!";
char destination[20];
strcpy(destination, source);
printf("Copied string is %s\n", destination);
return 0;
}
In the above code, strcpy(destination, source)
will copy the string from source
to destination
.
strcat()
strcat()
is a function that concatenates the source string to the end of the destination string. The destination string must be large enough to hold the resulting string. Here's an example of how to use strcat()
:
#include <string.h>
#include <stdio.h>
int main() {
char destination[20] = "Hello";
char source[] = ", World!";
strcat(destination, source);
printf("Resulting string is %s\n", destination);
return 0;
}
In the above code, strcat(destination, source)
will append the string from source
to the end of destination
.
strcmp()
strcmp()
is a function that compares two strings. The result of strcmp()
function is 0
if both strings are equal, less than 0
if the first string is less than the second string, and greater than 0
if the first string is greater than the second string. Here's an example of how to use strcmp()
:
#include <string.h>
#include <stdio.h>
int main() {
char string1[] = "Hello";
char string2[] = "World";
int result = strcmp(string1, string2);
printf("Result of comparison is %d\n", result);
return 0;
}
In the above code, strcmp(string1, string2)
will return a value less than 0
since the string "Hello" is less than "World" in lexicographical order.
These are just a few basic string functions in C. There are many others which you can explore as you delve deeper into C programming. Always remember that handling strings properly is a crucial part of writing efficient and effective C code.