String Functions
String Functions
We can use C's string handling library functions to handle strings. The string.h
library is used to perform string operations. It provides several functions for manipulating strings.
Following are some commonly used string handling functions:
-
strcat():
This function is used to concatenate the source string to the end of the target string. For example, “Hello” and “World” on concatenation would result in a string “HelloWorld”.
Here is how we can use the
strcat()
function:#include <stdio.h> #include <string.h> int main() { char s[] = "Hello"; char t[] = "World"; strcat(s, t); printf("String = %s", s); }
Output:
String = HelloWorld
-
strlen():
This function is used to count the number of characters present in a string.
Here is how we can use the
strlen()
function:#include <stdio.h> #include <string.h> int main() { char s[] = "Hello"; int len = strlen(s); printf("Length = %d", len); }
Output:
Length = 5
-
strcpy():
This function is used to copy the contents of one string into the other.
Here is how we can use the
strcpy()
function:#include <stdio.h> #include <string.h> int main() { char s[] = "CodeWithHarry"; char t[50]; strcpy(t, s); printf("Source string = %s\n", s); printf("Target string = %s", t); }
Output:
Source string = CodeWithHarry Target string = CodeWithHarry
-
strcmp():
This function is used to compare two strings to find out whether they are the same or different.
Here is how we can use the
strcmp()
function:#include <stdio.h> #include <string.h> int main() { char s[] = "Hello"; char t[] = "World"; int cmp = strcmp(s, t); printf("Comparison result = %d", cmp); }
Output:
Comparison result = -1
-
strrev():
This function is used to return the reverse of the string.
Here is how we can use the
strrev()
function:#include <stdio.h> #include <string.h> int main() { char s[] = "Hello"; printf("Reversed string = %s", strrev(s)); }
Output:
Reversed string = olleH