C String Functions
- Siddharth Sharma
- Nov 5, 2024
- 2 min read
String Functions :
C also has many useful string functions, which can be used to perform certain operations on strings.
To use them, you must include the <string.h> header file in your program:

String Length :
For example, to get the length of a string, you can use the strlen() function:
#include <stdio.h>
#include <string.h>
int main() {
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet));
return 0;
}हमने string/array का size प्राप्त करने के लिए sizeof का उपयोग किया। ध्यान दें कि sizeof और strlen अलग-अलग व्यवहार करते हैं, क्योंकि गिनती करते समय sizeof में \0 character भी शामिल होता है:
#include <stdio.h>
#include <string.h>
int main() {
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("Length is: %d\n", strlen(alphabet));
printf("Size is: %d\n", sizeof(alphabet));
return 0;
}
यह भी महत्वपूर्ण है कि आप जानते हैं कि sizeof हमेशा memory size (bytes में) लौटाएगा, न actual string length:
#include <stdio.h>
#include <string.h>
int main() {
char alphabet[50] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("Length is: %d\n", strlen(alphabet));
printf("Size is: %d\n", sizeof(alphabet));
return 0;
}
Concatenate Strings :
two strings को जोड़ने (combine) के लिए, आप strcat() function का उपयोग कर सकते हैं:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello ";
char str2[] = "World!";
// Concatenate str2 to str1 (the result is stored in str1)
strcat(str1, str2);
// Print str1
printf("%s", str1);
return 0;
}Note that the size of str1 should be large enough to store the result of the two strings combined (20 in our example)
Copy Strings :
एक string के value को दूसरे में copy करने के लिए, आप strcpy() function का उपयोग कर सकते हैं:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello World!";
char str2[20];
// Copy str1 to str2
strcpy(str2, str1);
// Print str2
printf("%s", str2);
return 0;
}Note that the size of str2 should be large enough to store the copied string (20 in our example).
Compare Strings :
To compare two strings, you can use the strcmp() function.
यदि two strings बराबर हैं तो यह 0 लौटाता है, अन्यथा वह value 0 नहीं है:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "Hi";
// Compare str1 and str2, and print the result
printf("%d\n", strcmp(str1, str2));
// Compare str1 and str3, and print the result
printf("%d\n", strcmp(str1, str3));
return 0;
}



Comments