Strings in C Programming

Character positions and null terminator in a C string

A string in C is an array of char values terminated by the null character \0. C has no separate built-in string type, so string operations work with character arrays and pointers.

Declare a String Top ↑

char name[] = {'p', 'l', 'u', 's', '2', 'n', 'e', 't', '\0'};
char site[10] = "plus2net";

Array indexes begin at 0. The literal "plus2net" contains 8 visible characters plus the terminating null character, so an array of at least 9 characters is required.

The Null Character Ends the String Top ↑

char name[10] = "plus2net";
name[3] = '\0';
printf("%s\n", name);

Output

plu

Placing \0 at index 3 makes string functions treat that position as the end.

Read Characters Until \0 Top ↑

#include <stdio.h>

int main(void) {
    char name[] = "plus2net";
    int i = 0;

    while (name[i] != '\0') {
        printf("%c ", name[i]);
        i++;
    }

    printf("\nCharacters: %d\n", i);
    return 0;
}

Output

p l u s 2 n e t
Characters: 8

Read a String Safely Top ↑

fgets() is useful when input may contain spaces because it limits the number of characters written to the array.

#include <stdio.h>
#include <string.h>

int main(void) {
    char name[40];

    printf("Enter your name: ");
    if (fgets(name, sizeof name, stdin) == NULL) {
        return 1;
    }

    name[strcspn(name, "\n")] = '\0';

    printf("Welcome %s\n", name);
    return 0;
}

Print a String Vertically and Count the Characters Top ↑

This restores the distinct vertical-printing example from the original pillar page.

#include <stdio.h>

int main(void) {
    char text[] = "Welcome";
    int i = 0;

    for (i = 0; text[i] != '\0'; i++) {
        printf("%c\n", text[i]);
    }

    printf("Total number of chars = %d\n", i);
    return 0;
}

Output

W
e
l
c
o
m
e
Total number of chars = 7

Standard String Length, Copy, Append and Compare Top ↑

Search and Parse Strings Top ↑

Duplicate and Modify Strings Top ↑

Legacy / Non-Standard String Functions Top ↑

Some older compilers provide the following functions. They are not part of older ISO C standards, so each tutorial also shows a portable modern replacement or explains the implementation requirement.

Practice C Strings Top ↑

Related Topic Top ↑

Arrays of strings in C are primarily part of the Array cluster, but they build directly on the character-array concepts covered here.





plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer