C Strings

C does not have a separate string type. A string is an array of characters which ends with a special null character '\0'. The null character tells where the string ends.

Declare a string

char name1[] = "Robin";                         // compiler adds '\0'
char name2[6] = {'R', 'o', 'b', 'i', 'n', '\0'};
char name3[20] = "Maria";                       // extra space is free

The word “Robin” has 5 letters, but needs 6 bytes, because of the null character.

Print a string

#include <stdio.h>

int main(void) {
    char city[] = "Delhi";

    printf("City: %s\n", city);
    printf("First letter: %c\n", city[0]);
    return 0;
}

Output:

Output of the above program is

City: Delhi
First letter: D

Go through the characters

#include <stdio.h>

int main(void) {
    char word[] = "Code";

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

Output:

Output of the above program is

C-o-d-e-

Size of array and length of string

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

int main(void) {
    char s[20] = "Hello";

    printf("sizeof = %zu\n", sizeof(s));
    printf("strlen = %zu\n", strlen(s));
    return 0;
}

Output:

Output of the above program is

sizeof = 20
strlen = 5

sizeof gives the full memory of the array. strlen() counts the characters before the null character.

Change a character

#include <stdio.h>

int main(void) {
    char s[] = "Cat";
    s[0] = 'B';
    printf("%s\n", s);
    return 0;
}

Output:

Output of the above program is

Bat

Note: You can change the characters of an array. But a string pointer like char *s = "Cat"; points to a read only text, and changing it is not allowed. You cannot assign strings with = after declaration, use strcpy().

Next: C String Input and Output.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.