🟡 Intermediate  ·  Lesson 22

Strings in C

Strings

What is a String in C?

C does not have a built-in string type like Java or Python. In C, a string is simply a character array that ends with a special null character '\\0' (null terminator). This null character marks the end of the string.

String Memory Layout
char name[] = "Gagan";
// Memory: G  a  g  a  n  \\0
//Index:   0  1  2  3  4   5
// The \\0 is automatically added at the end!
💡 Size = Length + 1

Always declare a char array one byte larger than the string length to accommodate the null terminator. For "Hello" (5 chars), declare char str[6].

Declaring and Initializing Strings

C Language
// Method 1: String literal (auto adds \\0)
char name[] = "Gagan";         // Size = 6 (5 + \\0)

// Method 2: Explicit size
char city[50] = "Aligarh";    // Size 50, can hold up to 49 chars

// Method 3: Char by char (must add \\0 manually!)
char str[6] = {'H','e','l','l','o','\\0'};

// Uninitilized (declare, fill later)
char input[100];              // Buffer for user input
⚠️ Cannot assign strings with =

After declaration, you cannot do name = "Rahul". Use strcpy(name, "Rahul") instead. The = operator only works during initialization.

String Input and Output

C Language – String I/O Methods
#include <stdio.h>
int main() {
    char name[50], city[50], sentence[200];

    // printf / scanf — reads until whitespace (one word only)
    printf("Enter first name: ");
    scanf("%s", name);          // No & needed for char array!
    printf("Hello, %s!\\n", name);

    // gets() — reads entire line including spaces (UNSAFE but simple)
    printf("Enter city: ");
    getchar();                   // Clear newline from buffer
    gets(city);
    puts(city);                  // puts adds \\n automatically

    // fgets() — SAFER, reads whole line, specify max chars
    printf("Enter sentence: ");
    fgets(sentence, sizeof(sentence), stdin);
    printf("You said: %s", sentence);

    return 0;
}
FunctionUsageHandles spaces?Safe?
scanf("%s")One word input❌ Stops at space⚠️ No buffer check
gets()Full line input✅ Yes❌ Unsafe (deprecated)
fgets()Full line with size limit✅ Yes✅ Safe (recommended)
printf("%s")Print string✅ Yes
puts()Print string + newline✅ Yes

String Functions (string.h)

Include #include <string.h> to use these.

Standard C Note

strrev(), strupr() and strlwr() are compiler-specific, not standard C. Use manual loops for portable programs.

C Language – String Functions Demo
#include <stdio.h>
#include <string.h>
int main() {
    char s1[50] = "Hello";
    char s2[50] = "World";

    printf("strlen(s1)       = %d\\n", (int)strlen(s1));    // 5
    printf("strcmp(s1,s2)    = %d\\n", strcmp(s1, s2));    // negative (H < W)
    strcat(s1, " World");
    printf("After strcat: %s\\n", s1);                   // "Hello World"
    strcpy(s2, "CodeKaFunda");
    printf("After strcpy: %s\\n", s2);                   // "CodeKaFunda"

    // Convert case (manual)
    for (int i = 0; s1[i]; i++) {
        if (s1[i] >= 'a' && s1[i] <= 'z')
            s1[i] -= 32;  // to uppercase
    }
    printf("Uppercase: %s\\n", s1);
    return 0;
}
strlen(s1) = 5 strcmp(s1,s2) = -15 After strcat: Hello World After strcpy: CodeKaFunda Uppercase: HELLO WORLD
FunctionSyntaxReturnsPurpose
strlen()strlen(s)length (int)String length (excl. \\0)
strcpy()strcpy(dest, src)dest pointerCopy src into dest
strcat()strcat(dest, src)dest pointerAppend src to dest
strcmp()strcmp(s1, s2)0/negative/positiveCompare (0 = equal)
strchr()strchr(s, ch)pointerFind a character
strstr()strstr(s, sub)pointerFind substring
strstr()strstr(s, sub)pointer or NULLFind substring

Complete Programs

Check Palindrome

C Language
#include <stdio.h>
#include <string.h>
int main() {
    char str[100], rev[100];
    printf("Enter string: ");
    scanf("%s", str);
    strcpy(rev, str);

    int i = 0, j = strlen(rev) - 1;
    while (i < j) {
        char temp = rev[i];
        rev[i] = rev[j];
        rev[j] = temp;
        i++;
        j--;
    }

    if (strcmp(str, rev) == 0)
        printf("%s is a Palindrome\\n", str);
    else
        printf("%s is NOT a Palindrome\\n", str);
    return 0;
}
Enter string: madam madam is a Palindrome

Summary

  • Strings in C = char arrays ending with '\\0' (null terminator)
  • Always allocate one extra byte for '\\0'
  • Use fgets() for safe string input with spaces
  • Include <string.h> for string functions
  • Key functions: strlen, strcpy, strcat, strcmp
  • Cannot use = to copy strings; use strcpy()

String क्या है?

C में Java या Python की तरह built-in string type नहीं है। C में string simply एक character array है जो special null character '\\0' से end होती है। यह null character string का अंत बताता है।

Memory Layout
char name[] = "Gagan";
// Memory: G  a  g  a  n  \\0
//Index:   0  1  2  3  4   5
// \\0 automatically add होता है!
💡 Size = Length + 1

हमेशा string length से एक byte बड़ा char array declare करें (null terminator के लिए)। "Hello" (5 chars) के लिए char str[6] declare करें।

Declare और Initialize

C Language
char name[] = "Gagan";        // Auto size = 6
char city[50] = "Aligarh";   // 50 chars की capacity
char input[100];             // User input के लिए buffer
⚠️ = से String Copy नहीं होती!

Declaration के बाद name = "Rahul" नहीं चलेगा। strcpy(name, "Rahul") use करें।

String Input और Output

C Language
char name[50], sentence[200];

// scanf — space तक ही पढ़ता है (एक word)
scanf("%s", name);     // char array में & की ज़रूरत नहीं!
printf("%s\\n", name);

// fgets — पूरी line पढ़ता है (spaces भी) — SAFE
fgets(sentence, sizeof(sentence), stdin);
puts(sentence);         // puts automatically \\n add करता है

String Functions (string.h)

#include <string.h> include करें।

Standard C Note

strrev(), strupr() और strlwr() standard C functions नहीं हैं। Portable programs के लिए manual loops use करें।

C Language – String Functions
char s1[50] = "Namaste", s2[50] = "Duniya";

printf("%d\\n", (int)strlen(s1));   // 7 — length
strcat(s1, " "); strcat(s1, s2);    // "Namaste Duniya"
strcpy(s2, "CodeKaFunda");          // s2 में copy
printf("%d\\n", strcmp(s1, s2));    // 0 = equal, non-zero = unequal
Functionकाम
strlen(s)String की length (\\0 छोड़कर)
strcpy(d,s)s को d में copy करना
strcat(d,s)s को d के अंत में जोड़ना
strcmp(s1,s2)Compare: 0=equal, <0=s1 छोटा, >0=s1 बड़ा
strchr(s,ch)Character search करना
strstr(s,sub)Substring search करना

Programs

C Language – Palindrome Check
#include <stdio.h>
#include <string.h>
int main() {
    char str[100], rev[100];
    scanf("%s", str);
    strcpy(rev, str);

    int i = 0, j = strlen(rev) - 1;
    while (i < j) {
        char temp = rev[i];
        rev[i] = rev[j];
        rev[j] = temp;
        i++;
        j--;
    }

    if(strcmp(str,rev)==0) printf("Palindrome hai!\\n");
    else                     printf("Palindrome nahi hai\\n");
    return 0;
}

सारांश

  • C में strings = '\\0' से end होने वाले char arrays
  • हमेशा '\\0' के लिए एक extra byte allocate करें
  • Spaces सहित input के लिए fgets() use करें
  • String functions के लिए <string.h> include करें
  • Key functions: strlen, strcpy, strcat, strcmp
← Back to C Tutorial