Chapter 8C Language Tutorial~1 min read
Strings in C
Strings — Character Arrays
C मध्ये string म्हणजे character array जी null character ('\0') ने संपते. Python सारखी built-in string type नाही — char array वापरतात. string.h header मध्ये string functions आहेत.
String declare आणि print करणे
c
#include <stdio.h>
#include <string.h> // string functions साठी
int main() {
// String declare करणे — extra 1 byte \0 साठी
char name[20] = "Rahul";
char city[] = "Pune"; // size auto
printf("Name: %s\n", name); // %s format specifier
printf("City: %s\n", city);
// Character by character access
printf("First char: %c\n", name[0]); // R
// scanf वापरून string input
char input[50];
printf("तुमचे नाव टाका: ");
scanf("%s", input); // string साठी & नको
printf("नमस्कार, %s!\n", input);
return 0;
}String Functions — string.h
Common string functions
c
#include <stdio.h>
#include <string.h>
int main() {
char s1[50] = "Hello";
char s2[] = "World";
// strlen — length किती?
printf("Length: %lu\n", strlen(s1)); // 5
// strcpy — copy करणे
char s3[50];
strcpy(s3, s1); // s3 = "Hello"
printf("Copied: %s\n", s3);
// strcat — जोडणे (concatenate)
strcat(s1, " ");
strcat(s1, s2); // s1 = "Hello World"
printf("Joined: %s\n", s1);
// strcmp — compare करणे
// 0 = equal, negative = s1 < s2, positive = s1 > s2
int result = strcmp("abc", "abc");
printf("Compare: %d\n", result); // 0 — equal
result = strcmp("abc", "xyz");
printf("Compare: %d\n", result); // negative — 'a' < 'x'
// strupr / strlwr — case बदलणे (non-standard)
char lower[] = "hello";
printf("Upper: ");
for (int i = 0; lower[i]; i++) {
printf("%c", lower[i] - 32); // ASCII trick
}
printf("\n");
return 0;
}📌
C मध्ये s1 = s2 ने string copy होत नाही! strcpy(s1, s2) वापरावा लागतो. = हे pointer assignment आहे, value copy नाही.
✅ Key Points — लक्षात ठेवा
- ▸String = char array + \0 (null terminator)
- ▸char name[20] — 20 characters साठी जागा (19 + \0)
- ▸strlen() — length, strcpy() — copy, strcat() — join
- ▸strcmp() — 0 means equal
- ▸#include <string.h> — string functions साठी
0/12 chapters पूर्ण