⬅️ Previous
C String Functions Explained with Examples
🧵 String Operations and Functions in C
🔹 What is a String in C?
In C, a string is a sequence of characters terminated by a null character '\0'
.
char name[10] = "Arif";
Here, name
contains: {'A', 'r', 'i', 'f', '\0'}
🔹 Declaring Strings
char str1[] = "Hello";
char str2[6] = {'H','e','l','l','o','\0'};
🔹 Input and Output of Strings
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
scanf("%s", name);
printf("Hello, %s\n", name);
return 0;
}
📌 Note: Use fgets()
instead of scanf()
if input has spaces:
fgets(name, sizeof(name), stdin);
🧰 Common String Functions in C
Add this header:
#include <string.h>
✅ 1. strlen() – String Length
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "OpenAI";
printf("Length = %lu\n", strlen(str));
return 0;
}
✅ 2. strcpy() – Copy One String to Another
char src[] = "Hello";
char dest[20];
strcpy(dest, src);
✅ 3. strcat() – Concatenate Strings
char a[50] = "Hello ";
char b[] = "World";
strcat(a, b);
✅ 4. strcmp() – Compare Strings
int result = strcmp("abc", "abc"); // 0
int result2 = strcmp("abc", "abd"); // negative
✅ 5. strchr() – Find Character in String
char *ptr = strchr("Bangladesh", 'g');
✅ 6. strstr() – Find Substring
char *sub = strstr("Programming", "gram");
❌ Bonus: strrev() – Reverse String (Non-standard)
char str[] = "OpenAI";
strrev(str);
🎯 Full Example Program
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "Hello";
char str2[100] = "World";
printf("str1: %s\n", str1);
printf("str2: %s\n", str2);
printf("Length of str1: %lu\n", strlen(str1));
strcpy(str2, str1);
printf("After strcpy, str2: %s\n", str2);
strcat(str1, " C");
printf("After strcat, str1: %s\n", str1);
if (strcmp(str1, str2) == 0)
printf("str1 and str2 are equal.\n");
else
printf("str1 and str2 are different.\n");
return 0;
}
🧠 Summary Table
Function | Purpose |
---|---|
strlen() | Get string length |
strcpy() | Copy one string to another |
strcat() | Append strings |
strcmp() | Compare two strings |
strchr() | Locate character in string |
strstr() | Find substring |
💡 Tips for Working with Strings
- Always ensure enough memory space.
- Include
<string.h>
for built-in functions. - Avoid buffer overflows.
- Prefer
fgets()
overgets()
for safer input.