Strings — Char Arrays & string.h

C-তে আসল string type নেই — শুধু convention

~40 min Advanced 18 practice problems Live code

1. C Has No String Type

C-তে "string" বলতে কোনো বিশেষ type নেই। এটি কেবল একটি char-এর array, যার শেষে '\0' (null byte) থাকে। এটাই একমাত্র convention।

'H'[0] 'i'[1] '!'[2] '\0'[3] — null terminator ?[4] garbage (ignored) char s[] = "Hi!"; Figure 16.1 — একটি null-terminated string-এর memory layout।
strlen("Hi!")-এর মান 3 — null byte গণনা করা হয় না, কিন্তু memory-তে সেই byte লাগেই। তাই একটি 10-অক্ষরের string সংরক্ষণ করতে কমপক্ষে ১১ byte buffer দরকার।

2. Literals vs Modifiable Arrays

literal_vs_array.c
#include <stdio.h>

int main(void) {
    char  a[] = "hello";     // a copy on the stack — modifiable
    char *p = "hello";      // pointer to read-only memory

    a[0] = 'H';                // OK
    printf("%s\n", a);

    // p[0] = 'H';  // UB — may crash on most systems
    printf("%s\n", p);
    return 0;
}
String literal is read-only char *p = "hello"; — p pointer-টি সাধারণত read-only memory-র দিকে নির্দেশ করে। *p দিয়ে modify করতে চাইলে undefined behavior / crash হতে পারে। Modify করার দরকার হলে char a[] = "hello"; ব্যবহার করুন।

3. The string.h Library

FunctionPurposeSafety
strlen(s)length (without '\0')safe
strcpy(dst, src)copy⚠ unsafe — no size
strncpy(dst, src, n)copy up to nbetter
strcat(dst, src)append⚠ unsafe
strncat(dst, src, n)append up to nbetter
strcmp(a, b)<0, 0, >0 comparesafe
strchr(s, c)find a charsafe
strstr(h, n)find substringsafe
snprintf(buf, n, fmt, …)safe formatted print✅ recommended
Rule gets ব্যবহার করবেন না (ইতিমধ্যে standard থেকে বাদ)। strcpy / strcat-এর জায়গায় সবসময় snprintf বা strncpy/strncat ব্যবহার করুন এবং buffer size জানুন।

4. Implementing strlen Yourself

my_strlen.c
#include <stdio.h>
#include <stddef.h>

size_t my_strlen(const char *s) {
    const char *p = s;
    while (*p) p++;
    return p - s;
}

int main(void) {
    printf("%zu\n", my_strlen("ABCL TECH"));
    printf("%zu\n", my_strlen(""));
    return 0;
}

5. Reading Strings Safely

safe_read.c — stdin: Hello from Dhaka
#include <stdio.h>
#include <string.h>

int main(void) {
    char buf[128];
    if (fgets(buf, sizeof buf, stdin)) {
        size_t n = strlen(buf);
        if (n && buf[n - 1] == '\n') buf[--n] = '\0';
        printf("got %zu chars: \"%s\"\n", n, buf);
    }
    return 0;
}

6. Practice Problems

  1. Implement my_strlen.
    my_strlen লিখুন।
    ✨ Show Answer

    উপরের Section 4-এর কোডই সম্পূর্ণ উত্তর।

  2. Implement my_strcpy.
    my_strcpy লিখুন।
    ✨ Show Answer
    my_strcpy.c
    #include <stdio.h>
    char *my_strcpy(char *d, const char *s) {
        char *r = d;
        while ((*d++ = *s++));
        return r;
    }
    int main(void) {
        char buf[64];
        my_strcpy(buf, "Hello, Bangladesh!");
        puts(buf);
        return 0;
    }
  3. Implement my_strcmp.
    my_strcmp লিখুন।
    ✨ Show Answer
    my_strcmp.c
    #include <stdio.h>
    int my_strcmp(const char *a, const char *b) {
        while (*a && *a == *b) { a++; b++; }
        return (unsigned char)*a - (unsigned char)*b;
    }
    int main(void) {
        printf("%d\n", my_strcmp("abc", "abd"));
        printf("%d\n", my_strcmp("abc", "abc"));
        return 0;
    }
  4. Implement my_strcat.
    my_strcat লিখুন।
    ✨ Show Answer
    my_strcat.c
    #include <stdio.h>
    char *my_strcat(char *d, const char *s) {
        char *r = d;
        while (*d) d++;
        while ((*d++ = *s++));
        return r;
    }
    int main(void) {
        char buf[64] = "Hello, ";
        my_strcat(buf, "Bangladesh!");
        puts(buf);
        return 0;
    }
  5. Count vowels in a string.
    একটি string-এ vowel গুনুন।
    ✨ Show Answer
    vowels.c
    #include <stdio.h>
    #include <ctype.h>
    int main(void) {
        const char *s = "Hello Bangladesh";
        int c = 0;
        for (; *s; s++) {
            char lc = tolower((unsigned char)*s);
            if (lc=='a'||lc=='e'||lc=='i'||lc=='o'||lc=='u') c++;
        }
        printf("%d\n", c);
        return 0;
    }
  6. Count words in a string (separated by whitespace).
    Whitespace দিয়ে আলাদা হওয়া শব্দ গুনুন।
    ✨ Show Answer
    wordcount.c
    #include <stdio.h>
    #include <ctype.h>
    int main(void) {
        const char *s = "ABCL TECH   Free  C  course";
        int in_word = 0, count = 0;
        for (; *s; s++) {
            if (isspace((unsigned char)*s)) in_word = 0;
            else if (!in_word) { in_word = 1; count++; }
        }
        printf("words = %d\n", count);
        return 0;
    }
  7. Check if a string is a palindrome (ignore case).
    Case উপেক্ষা করে palindrome check করুন।
    ✨ Show Answer
    pal_ci.c
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    int is_pal(const char *s) {
        size_t i = 0, j = strlen(s); if (j == 0) return 1;
        j--;
        while (i < j) {
            if (tolower((unsigned char)s[i]) != tolower((unsigned char)s[j])) return 0;
            i++; j--;
        }
        return 1;
    }
    int main(void) {
        printf("%d\n", is_pal("Madam"));
        printf("%d\n", is_pal("hello"));
        return 0;
    }
  8. Reverse a string in place.
    In-place string reverse করুন।
    ✨ Show Answer
    rev.c
    #include <stdio.h>
    #include <string.h>
    int main(void) {
        char s[] = "ABCL TECH";
        size_t i = 0, j = strlen(s) - 1;
        while (i < j) { char t = s[i]; s[i++] = s[j]; s[j--] = t; }
        puts(s);
        return 0;
    }
  9. Convert a string to upper case — no library function.
    Library function ছাড়াই string uppercase করুন।
    ✨ Show Answer
    upper.c
    #include <stdio.h>
    int main(void) {
        char s[] = "hello";
        for (char *p = s; *p; p++)
            if (*p >= 'a' && *p <= 'z') *p -= 32;
        puts(s);
        return 0;
    }
  10. Parse a string of digits to an integer (like atoi).
    Digit-এর string থেকে integer (atoi-এর মতো) বের করুন।
    ✨ Show Answer
    my_atoi.c
    #include <stdio.h>
    int my_atoi(const char *s) {
        int sign = 1, n = 0;
        while (*s == ' ') s++;
        if (*s == '-') { sign = -1; s++; }
        else if (*s == '+') s++;
        while (*s >= '0' && *s <= '9') { n = n * 10 + (*s++ - '0'); }
        return sign * n;
    }
    int main(void) {
        printf("%d\n", my_atoi(" -2026abc"));
        printf("%d\n", my_atoi("42"));
        return 0;
    }
  11. Check if one string is an anagram of another.
    দুটি string একে অপরের anagram কি না যাচাই করুন।
    ✨ Show Answer
    anagram.c
    #include <stdio.h>
    #include <string.h>
    int anagram(const char *a, const char *b) {
        if (strlen(a) != strlen(b)) return 0;
        int cnt[256] = {0};
        for (; *a; a++) cnt[(unsigned char)*a]++;
        for (; *b; b++) if (--cnt[(unsigned char)*b] < 0) return 0;
        return 1;
    }
    int main(void) {
        printf("%d\n", anagram("listen", "silent"));
        printf("%d\n", anagram("abc", "abd"));
        return 0;
    }
  12. Encode a string with Caesar cipher (shift = 3).
    Caesar cipher (shift = 3) দিয়ে একটি string encrypt করুন।
    ✨ Show Answer
    caesar.c
    #include <stdio.h>
    int main(void) {
        char s[] = "Hello, World";
        for (char *p = s; *p; p++) {
            if (*p >= 'a' && *p <= 'z') *p = 'a' + (*p - 'a' + 3) % 26;
            else if (*p >= 'A' && *p <= 'Z') *p = 'A' + (*p - 'A' + 3) % 26;
        }
        puts(s);
        return 0;
    }
  13. Find the first non-repeating character in a string.
    প্রথম non-repeating character খুঁজে বের করুন।
    ✨ Show Answer
    first_unique.c
    #include <stdio.h>
    int main(void) {
        const char *s = "swiss";
        int cnt[256] = {0};
        for (const char *p = s; *p; p++) cnt[(unsigned char)*p]++;
        for (const char *p = s; *p; p++)
            if (cnt[(unsigned char)*p] == 1) { printf("%c\n", *p); return 0; }
        puts("none");
        return 0;
    }
  14. Compute the frequency of each character.
    প্রতিটি character-এর frequency বের করুন।
    ✨ Show Answer
    freq.c
    #include <stdio.h>
    int main(void) {
        const char *s = "programming";
        int cnt[256] = {0};
        for (; *s; s++) cnt[(unsigned char)*s]++;
        for (int i = 0; i < 256; i++)
            if (cnt[i]) printf("'%c' = %d\n", i, cnt[i]);
        return 0;
    }
  15. Show how strcpy can overflow a buffer — then fix with snprintf.
    দেখান strcpy কীভাবে buffer overflow করে, তারপর snprintf দিয়ে ঠিক করুন।
    ✨ Show Answer
    // ❌ Buffer overflow — UB
    char buf[8];
    strcpy(buf, "this is too long");    // writes past buf
    
    // ✅ Safe — truncates to fit, always null-terminates
    char buf[8];
    snprintf(buf, sizeof buf, "%s", "this is too long");

    snprintf buffer size জানে, তাই overflow হতে দেয় না এবং সবসময় শেষে '\0' বসায়।

  16. Why are string literals stored in read-only memory?
    String literal কেন read-only memory-তে রাখা হয়?
    ✨ Show Answer

    Compiler সাধারণত একই literal একাধিকবার ব্যবহার হলে একটি কপিই রাখে (string pooling) — যাতে program-এর size ছোট থাকে। Read-only রাখার মাধ্যমে accidental modification আটকানো হয় এবং optimization করা সহজ হয়। মডিফাই করতে চাইলে char arr[] ব্যবহার করুন।

  17. What is the difference between "" and '\0'?
    "" এবং '\0'-এর পার্থক্য কী?
    ✨ Show Answer

    "" হলো একটি string literal — মেমরিতে একটি একক '\0' byte, const char *-এ decay হয়। '\0' হলো একটি single character (int value 0)। "" address, '\0' value।

  18. Why does char *s = "hi"; s[0] = 'H'; sometimes work and sometimes crash?
    এই code কখনো কাজ করে, কখনো crash করে — কেন?
    ✨ Show Answer

    এটি undefined behavior। কিছু compiler/flag-এ literal modifiable হতে পারে (যদিও এটি অনাকাঙ্ক্ষিত), অন্যগুলিতে literal read-only segment-এ বসে — সেখানে লিখতে গেলে segmentation fault হয়। "কখনো কাজ করে" মানেই সঠিক নয় — আচরণ অনির্ধারিত। সবসময় char s[] = "hi"; ব্যবহার করুন যদি modify করতে চান।

Glossary (শব্দকোষ)

TermMeaningবাংলায়
StringA sequence of chars ending with a null byte.Null byte-এ শেষ হওয়া char-এর ক্রম।
Char ArrayA modifiable array of characters used to store a string.String রাখার পরিবর্তনযোগ্য char array।
Null Terminator ('\0')The byte that marks the end of a string.String-এর শেষ চিহ্নিত byte।
String LiteralQuoted string in source code — typically read-only.Source code-এ quote-এর মধ্যে থাকা string — সাধারণত read-only।
string.hThe standard header for string functions.String functions-এর standard header।
strlenReturns string length (not counting '\0').String-এর দৈর্ঘ্য (null বাদে)।
strcpy / strncpyCopies one string into another (size-aware variant).String কপি করা (size-aware রূপ আছে)।
strcat / strncatConcatenates strings.String জুড়ে দেওয়া।
strcmp / strncmpCompares strings lexicographically.Lex-ভাবে string তুলনা করে।
strchr / strstrSearch for a character / substring.Character / substring খুঁজে বের করা।
Buffer OverflowWriting past a string buffer — undefined behavior.Buffer-এর সীমার বাইরে লেখা — undefined behavior।
Mutable vs ImmutableChar arrays are mutable; string literals must not be modified.Char array পরিবর্তনযোগ্য; literal অপরিবর্তনীয়।

Summary — Module 16

Strings in C are char arrays terminated by '\0'. String literals are read-only; char arrays are modifiable. Master string.h, but prefer size-aware functions. Always know your buffer size.

Next Module → Dynamic Memory — malloc, calloc, realloc, free।