C लाइब्रेरी फंक्शन char *strncpy(char *dest, const char *src, size_t n) स्रोत स्ट्रिंग (src) से गंतव्य स्ट्रिंग (dest) में n कैरेक्टर्स तक कॉपी करता है। यदि src की लंबाई n से कम है, तो dest का शेष भाग नल बाइट्स से भरा जाता है।
घोषणा
char stringname [size];
आरंभीकरण
- सिंगल कैरेक्टर:
char string[10] = {'H','e','l','l','o','\0'} - स्ट्रिंग कॉन्स्टेंट:
char string[10] = "Hello";
एक्सेस करना - "%s" कंट्रोल स्ट्रिंग का उपयोग।
strncpy() फंक्शन
- सोर्स स्ट्रिंग के 'n' कैरेक्टर्स को डेस्टिनेशन स्ट्रिंग में कॉपी करता है।
- डेस्टिनेशन स्ट्रिंग की लंबाई सोर्स स्ट्रिंग से अधिक या बराबर होनी चाहिए।
सिंटैक्स
strncpy(destination_string, source_string, n);
उदाहरण प्रोग्राम
#include <string.h>
#include <stdio.h>
int main() {
char a[50], b[50];
printf("Enter a string: ");
fgets(a, 50, stdin);
a[strcspn(a, "\n")] = 0; // न्यूलाइन हटाएं
strncpy(b, a, 3);
b[3] = '\0'; // नल टर्मिनेटर सुनिश्चित करें
printf("Copied string = %s", b);
return 0;
}
आउटपुट
Enter a string: Hello Copied string = Hel
सबस्ट्रिंग निकालने के लिए उपयोग
strncpy() सबस्ट्रिंग निकालने के लिए भी उपयोगी है।
उदाहरण 1
char result[10], s1[15] = "Jan 10 2010"; strncpy(result, &s1[4], 2); // इंडेक्स 4 से 2 कैरेक्टर्स result[2] = '\0';
आउटपुट: Result = 10
उदाहरण 2: जटिल सबस्ट्रिंग निष्कर्षण
#include <stdio.h>
#include <string.h>
void main(){
char source[45], destination[50];
char destination1[10], destination2[10], destination3[10], destination4[10];
printf("Enter the source string: ");
fgets(source, 45, stdin);
source[strcspn(source, "\n")] = 0;
// पहले 2 कैरेक्टर्स निकालें
strncpy(destination1, source, 2);
destination1[2] = '\0';
printf("First destination value: %s\n", destination1);
// इंडेक्स 8 से 1 कैरेक्टर
strncpy(destination2, &source[8], 1);
destination2[1] = '\0';
printf("Second destination value: %s\n", destination2);
// इंडेक्स 12 से 1 कैरेक्टर
strncpy(destination3, &source[12], 1);
destination3[1] = '\0';
printf("Third destination value: %s\n", destination3);
// कन्कैटनेट करें
strcat(destination1, destination2);
strcat(destination1, destination3);
printf("Modified destination string: %s\n", destination1);
}
आउटपुट
Enter the source string: Tutorials Point The first destination value is: Tu The second destination value is: s The third destination value is: i The modified destination string: Tusi
महत्वपूर्ण चेतावनी
- यदि n सोर्स स्ट्रिंग की लंबाई से अधिक है, तो strncpy डेस्टिनेशन को नल बाइट्स से पैड करता है।
- यदि n सोर्स स्ट्रिंग की लंबाई के बराबर या कम है, तो डेस्टिनेशन नल-टर्मिनेटेड नहीं होगा - आपको मैन्युअली
dest[n] = '\0'सेट करना होगा। - सुरक्षित विकल्प: strlcpy() (BSD) या snprintf()।