String Operations in C
1. String Length using strlen()
This program uses strlen() to find the length of a string.
#include <stdio.h>
#include <string.h>
int main() {
char str[50] = "Hello World";
printf("Length: %lu", strlen(str));
return 0;
}
Output:
Length: 11
2. Copy String using strcpy()
strcpy() copies the content of one string to another.
#include <stdio.h>
#include <string.h>
int main() {
char src[50] = "C Programming";
char dest[50];
strcpy(dest, src);
printf("Copied String: %s", dest);
return 0;
}
Output:
Copied String: C Programming
3. String Concatenation using strcat()
strcat() joins two strings together.
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello ";
char str2[50] = "World";
strcat(str1, str2);
printf("Concatenated String: %s", str1);
return 0;
}
Output:
Concatenated String: Hello World
4. Compare Strings using strcmp()
strcmp() compares two strings lexicographically.
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "banana";
int result = strcmp(str1, str2);
if (result == 0) printf("Strings are equal");
else printf("Strings are not equal");
return 0;
}
Output:
Strings are not equal
5. Reverse a String
strrev() reverses the order of characters in a string.
#include <stdio.h>
#include <string.h>
int main() {
char str[50] = "Hello";
strrev(str);
printf("Reversed String: %s", str);
return 0;
}
Output:
Reversed String: olleH
6. Convert String to Uppercase
toupper() converts each character to uppercase.
#include <stdio.h>
#include <ctype.h>
int main() {
char str[50] = "hello";
for(int i = 0; str[i]; i++) {
str[i] = toupper(str[i]);
}
printf("Uppercase: %s", str);
return 0;
}
Output:
Uppercase: HELLO
7. Convert String to Lowercase
tolower() converts each character to lowercase.
#include <stdio.h>
#include <ctype.h>
int main() {
char str[50] = "HELLO";
for(int i = 0; str[i]; i++) {
str[i] = tolower(str[i]);
}
printf("Lowercase: %s", str);
return 0;
}
Output:
Lowercase: hello
8. Count Vowels in a String
This program counts vowels in a string.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char str[50] = "Hello World";
int count = 0;
for(int i = 0; str[i]; i++) {
char ch = tolower(str[i]);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') count++;
}
printf("Vowels: %d", count);
return 0;
}
Output:
Vowels: 3
9. Check Palindrome String
A palindrome reads the same forwards and backwards.
#include <stdio.h>
#include <string.h>
int main() {
char str[50] = "madam";
char rev[50];
strcpy(rev, str);
strrev(rev);
if(strcmp(str, rev) == 0)
printf("Palindrome");
else printf("Not Palindrome");
return 0;
}
Output:
Palindrome