C Language में String एक character का collection होता है जो एक single variable में store होता है।
आसान शब्दों में कहें तो string का मतलब होता है letters, words या sentences का समूह, जैसे: "hello", "India", "1234" आदि।
C में string को char array
के रूप में store किया जाता है।
char name[20];
इसका मतलब है कि हम एक ऐसा array बना रहे हैं जिसमें 20 characters store हो सकते हैं।
char name[] = "Rahul";
यहाँ हमने "Rahul" नाम की string को array में store किया है। C automatically '\0' (null character) को अंत में जोड़ देता है जिससे यह पता चलता है कि string खत्म हो गई है।
#include <stdio.h>
int main() {
char name[] = "Rahul";
printf("Name is: %s", name);
return 0;
}
Output: Name is: Rahul
यहाँ %s
format specifier का use किया गया है जो string print करने के लिए होता है।
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
scanf("%s", name);
printf("Hello, %s!", name);
return 0;
}
Output: यदि आप "Amit" टाइप करते हैं, तो Output होगा: Hello, Amit!
Note: scanf()
space के बाद का input नहीं लेता।
#include <stdio.h>
int main() {
char name[50];
printf("Enter full name: ");
gets(name);
printf("Welcome, %s", name);
return 0;
}
Note: gets()
function unsafe माना जाता है। इसके बजाय आप fgets()
का उपयोग कर सकते हैं।
#include <stdio.h>
int main() {
char name[50];
printf("Enter your full name: ");
fgets(name, sizeof(name), stdin);
printf("Welcome, %s", name);
return 0;
}
fgets()
space सहित पूरा input लेता है और इसे buffer overflow से भी बचाता है।
C में strings पर काम करने के लिए <string.h>
header file में कई functions होते हैं:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello";
int len = strlen(str);
printf("Length of string = %d", len);
return 0;
}
Output: Length of string = 5
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "C Language";
char destination[20];
strcpy(destination, source);
printf("Copied string: %s", destination);
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char first[20] = "Hello ";
char second[] = "World!";
strcat(first, second);
printf("Full string: %s", first);
return 0;
}
Strings real-world applications में बहुत जरूरी होते हैं, जैसे – user input, message display, file names आदि। C में string handling थोड़ा अलग होता है क्योंकि यहाँ string एक character array होता है। लेकिन अगर आप ऊपर दिए गए examples को खुद से run करके देखें, तो string बहुत ही आसान concept है।