![]() |
Strings in C language |
Strings
String is a sequence of character that is considered as a single data item.
String is representing of character array.
Declaration
char string name[size];
Example:- char city[9] = " NEW YORK " ;
Strings Functions
Function Actions
- Strcat() It combined two string
- Strcmp() It compare two string
- Strcpy() It copy one string to another string
- Strlen() It counts character in a strings
strcat() function
The strcat() function joins two string together.
Strcat(string_1, string_2);
Example:
#include <stdio.h>#include <string.h>
int main() {
char str1[] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2); // Concatenates str2 to str1
printf("Concatenated String: %s\n", str1);
return 0;
}
Result : Concatenated String: Hello, World!
strcmp() function
The strcmp() function compares two strings.
Strcmp(string_1, string_2);
Example
#include <stdio.h>#include <string.h>
int main() {
char str1[] = "Apple";
char str2[] = "Banana";
int result = strcmp(str1, str2); // Compares str1 and str2
if (result == 0)
printf("Strings are equal\n");
else if (result > 0)
printf("str1 is greater\n");
else
printf("str2 is greater\n");
return 0;
}
Result: str2 is greater
strcpy() function
The strcpy() function works almost like a string assignment oprater.
strcpy(string_1, string_2);
Example
#include <stdio.h>#include <string.h>
int main() {
char str1[] = "Hello";
char str2[20];
strcpy(str2, str1); // Copies str1 to str2
printf("Copied String: %s\n", str2);
return 0;
}
Result: Copied String: Hello
strlen() function
The strlen() function count and return the number of string.
n = strlen(string);
Example
#include <stdio.h>#include <string.h>
int main() {
char str[] = "Programming";
int length = strlen(str); // Finds length of str
printf("Length of string: %d\n", length);
return 0;
}
Result: Length of string: 11