🟡 Intermediate  ·  Lesson 22

Strings in C

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, "CodingEasily");
    printf("After strcpy: %s\\n", s2);                   // "CodingEasily"

    // 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: CodingEasily 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()

Frequently Asked Questions

What is a string in C?
A string in C is an array of characters ending with a special null character '\0', which marks where the text stops. For example char name[] = "Amit"; stores five characters: the four letters plus the terminating null.
What is the null terminator in a C string?
The null terminator is the character '\0' automatically placed at the end of every string literal. It tells string functions where the text ends, which is why a character array must have room for it in addition to the visible characters.
How do you read a string with spaces in C?
scanf("%s", ...) stops at the first space, so it only reads one word. To read a full line including spaces you use fgets(str, size, stdin), which reads until a newline or the buffer is full and is also safer against overflow.
How do you find the length of a string in C?
You use strlen from <string.h>, which counts characters up to but not including the null terminator. So strlen("Amit") returns 4, even though the array itself uses five bytes including the '\0'.
What is the difference between a character array and a string in C?
Every C string is a character array, but a character array is only a proper string when it ends with a null terminator. If you fill an array with characters and forget the '\0', string functions will read past the end and misbehave.
← Back to C Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.