string.h लाइब्रेरी फंक्शन्स
स्ट्रिंग हैंडलिंग के लिए पूर्वनिर्धारित फंक्शन्स string.h में उपलब्ध हैं।
प्रमुख फंक्शन्स
1. strlen() - स्ट्रिंग लंबाई
स्ट्रिंग में कैरेक्टर्स की संख्या लौटाता है (नल टर्मिनेटर छोड़कर)।
int strlen(const char *str);
char a[30] = "Hello";
int l = strlen(a); // 5
2. strcpy() - स्ट्रिंग कॉपी
सोर्स स्ट्रिंग को डेस्टिनेशन में कॉपी करता है। डेस्टिनेशन का आकार सोर्स से बड़ा या बराबर होना चाहिए।
strcpy(dest, src);
char a[50], b[50];
strcpy(b, a); // a को b में कॉपी
3. strncpy() - n कैरेक्टर्स कॉपी
सोर्स के पहले n कैरेक्टर्स डेस्टिनेशन में कॉपी करता है।
strncpy(dest, src, n);
strncpy(b, a, 3); // पहले 3 कैरेक्टर्स
b[3] = '\0'; // मैन्युअली नल टर्मिनेट
4. strcat() - स्ट्रिंग कॉनकैटेनेशन
दो स्ट्रिंग्स जोड़ता है। परिणाम डेस्टिनेशन में स्टोर होता है।
strcat(dest, src);
char a[50] = "Hello";
char b[20] = "Good Morning";
strcat(a, b); // a = "HelloGood Morning"
5. strncat() - n कैरेक्टर्स कॉनकैटेनेट
strncat(dest, src, n);
6. strcmp() - स्ट्रिंग तुलना
दो स्ट्रिंग्स की तुलना करता है। पहले नॉन-मैचिंग कैरेक्टर्स का ASCII अंतर लौटाता है।
int strcmp(const char *s1, const char *s2);
- 0: दोनों समान
- >0: s1 > s2
- <0: s1 < s2
7. strncmp() - n कैरेक्टर्स तुलना
strncmp(s1, s2, n);
8. strrev() - स्ट्रिंग रिवर्स
strrev(str);
9. strstr() - सबस्ट्रिंग खोज
मेन स्ट्रिंग में सबस्ट्रिंग ढूंढता है। पहली घटना का पॉइंटर लौटाता है, नहीं मिलने पर NULL।
char *found = strstr(main_str, sub_str);
पूर्ण उदाहरण प्रोग्राम
#include <stdio.h>
#include <string.h>
int main() {
char a[50], b[50];
int d;
printf("Enter 2 strings: ");
scanf("%s %s", a, b);
d = strcmp(a, b);
if (d == 0)
printf("%s equals %s", a, b);
else if (d > 0)
printf("%s greater than %s", a, b);
else
printf("%s less than %s", a, b);
return 0;
}
आउटपुट
Enter 2 strings: apple ball apple is less than ball
strstr() उदाहरण
#include <stdio.h>
#include <string.h>
int main() {
char a[30], b[30];
char *found;
printf("Enter main string: "); gets(a);
printf("Enter substring to search: "); gets(b);
found = strstr(a, b);
if (found)
printf("'%s' found in '%s' at position %ld", b, a, found - a);
else
printf("Substring not found");
return 0;
}
आउटपुट
Enter main string: how are you Enter substring: you 'you' found in 'how are you' at position 8