Menu
Coddy logo textTech

C-style Strings Part 1

Part of the Fundamentals section of Coddy's C++ journey — lesson 67 of 74.

C-style strings are created with the char type instead of string. They end with a special character called the null character ('\0').

This character marks the end of the string. C-style strings are often referred to as "null-terminated strings."

For example a simple declaration:

char str1[] = "Hello";

str1 is declared without a specific size. The compiler automatically determines the size based on the initializer (including the null character).

Example of explicitly initialize with characters:

char str2[6] = {'W', 'o', 'r', 'l', 'd', '\0'};

str2 is declared with a size of 6 and explicitly initialized with characters, including the null character at the end.

Example of partly initialized:

char str3[10] = "Coddy";

str3 is declared with a size of 10, but only the first 6 characters are initialized. The rest of the array is filled with null characters.

To use C-style strings we need to include it:

#include <cstring>

After the include, we can use the strlen function to get the length of a C-style string:

std::cout << strlen(str1); // Output: 5
challenge icon

Challenge

Easy

Create a function named printStringInfo that takes a C-style string as input and does the following:

  1. String:  followed by the original string.
  2. Length:  followed by the result of strlen(str).
  3. Character at index 4:  followed by the character at that position.
  4. Modified string:  followed by the string after changing the first character to X.

Cheat sheet

C-style strings are created with the char type and end with the null character '\0'. They are null-terminated strings.

Declaration without specific size (compiler determines size):

char str1[] = "Hello";

Explicit initialization with characters:

char str2[6] = {'W', 'o', 'r', 'l', 'd', '\0'};

Partial initialization (remaining filled with null characters):

char str3[10] = "Coddy";

To use C-style string functions, include:

#include <cstring>

Get string length using strlen():

std::cout << strlen(str1); // Output: 5

Try it yourself

#include <iostream>
#include <cstring>

void printStringInfo(char str[]) {
    // Print the string
    

    // Print the length of the string
    

    // Print the character at index 4
    

    // Modify the first character to 'X'
    

    // Print the modified string
    
}

int main() {
    char message[] = "Hello, World!";

    printStringInfo(message);

    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals