khuang8493
6/26/2018 - 12:05 AM

String and Char Array

How to put a string into an array of char.

String and Char

A string is just an array of char, with the last char '\0' to mark the end of this string. Therefore if we want to put a string of 4 characters into the memory, we need to define an array of char of "5" instead of 4, because we need an extra char in the end for '\0' to mark the end of the string.
For example, we can define a char array:

char initials[4];

So that leaves room in the memory to put a string of maximum 3 chars, and a '\0' in the last char. Be aware that here there's room for maximum 3 char string, but the string doesn't have to be 3 chars long. It can be 1 char, or 2 char. If it's 1 or 2 char long, the '\0' will not be put in the 4th space of the string, but will put on 2nd or 3rd space of the string.

When we defined an array of char, and has put a string in it, we can print it out as a string:

char initials[4];

{
	codes to put some chars and '\0' into this char array;
}

printf("%s\n", initials); 

So here we just use "initials" directly as a string. This array is not just an array of char anymore, but a whole complete string. We don't need a "for" loop to print each char out, just print it at once as a whole single string.

The complete code for initials is as follows. Notice that we put each char into the initials[] array, and at last we put manually '\0' into the last char in initials[]. Then after that "initials" becomes a string because there is a '\0' in the end.

// Extracts a user's initials

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

int main(void)
{
    char initials[4];
    string s = get_string("Name: ");
    int length = 0;
    for (int i = 0, n = strlen(s); i < n; i++)
    {
        if (isupper(s[i]))
        {
            initials[length] = s[i];
            length++;
        }
    }
    initials[length] = '\0';
    printf("%s\n", initials);
}