Curriculum
Course: Learn C++
Login

Curriculum

Learn C++

Text lesson

Understanding the Strings in C++

In this lesson, you will learn

  • C-style strings
  • C++ std::string class

 

In C++, strings can be created in two main ways: using C-style strings (character arrays) and using the C++ std::string class. Let’s go through both methods with examples.

StringInC++

 

1. C-Style Strings (Character Arrays)

In C++, C-style strings (character arrays) can be created in various ways. Here are the different methods:

1. Direct Initialization

You can directly initialize a character array with a string literal. The compiler automatically adds the null terminator ('\0').

Example:

#include<iostream>

int main() {
    // Direct initialization with a string literal
    char str[] = "Hello, World!";
    
    std::cout << "C-style string: " << str << std::endl;
    return 0;
}

Explanation:

  • The character array str is automatically sized to include the null terminator ('\0').
  • The string literal "Hello, World!" is stored in the array str.

 

 

2. Character-by-Character Initialization

You can manually assign each character to specific positions in the array and ensure you include the null terminator at the end.

Example:

#include<iostream>

int main() {
    // Character-by-character initialization
    char str[6]; // Array size must be at least 6 (5 characters + 1 null terminator)
    str[0] = 'H';
    str[1] = 'e';
    str[2] = 'l';
    str[3] = 'l';
    str[4] = 'o';
    str[5] = '\0'; // Null terminator
    
    std::cout << "C-style string: " << str << std::endl;
    return 0;
}

Explanation:

  • The array size must be specified, and it should be large enough to hold the characters and the null terminator.
  • You need to manually place the null terminator ('\0') to indicate the end of the string.

 

 

3. Partial Initialization

You can partially initialize a character array and leave the rest uninitialized. However, you must include the null terminator manually.

Example:

#include<iostream>

int main() {
    // Partial initialization
    char str[10] = {'H', 'e', 'l', 'l', 'o', '\0'};
    
    std::cout << "C-style string: " << str << std::endl;
    return 0;
}



Explanation:

  • The first five elements are initialized with characters, and the sixth element is the null terminator.
  • The remaining elements of the array remain uninitialized but are irrelevant because the string ends at the null terminator.

 

 

4. String Copy using strcpy

You can create an empty character array and then copy a string into it using the strcpy function from the C library.

Example:

#include<iostream>
#include<cstring>  // Include the C string library

int main() {
    // Creating an empty character array
    char str[20];
    
    // Copying a string using strcpy
    strcpy(str, "Hello, World!");
    
    std::cout << "C-style string: " << str << std::endl;
    return 0;
}

Explanation:

  • strcpy is used to copy the string "Hello, World!" into the character array str.
  • The array str should be large enough to hold the copied string and the null terminator.

 

2. C++ Style String(Using string class)

C++ provides a std::string class in the Standard Library, which simplifies string manipulation by automatically handling memory management and providing various functions for string operations.

Example: Creating String in C++

#include<iostream>
#include<string>
using namespace std;

int main() {
    // Creating a C++ string
    string str1 = "Hello, World!";
    
    // You can also declare an empty string and assign a value later
    string str2;
    str2 = "Hello";
    
    // Concatenating strings
    string str3 = str2 + ", C++!";

    //Creates a copy of another string
    string str4 = str3;

    //Creates a string with multiple repetitions of a character
    string str5(5, 'A');  // "AAAAA"
    
    // Printing C++ strings
    cout << "C++ string 1: " << str1 <<endl;
    cout << "C++ string 2: " << str2 <<endl;
    cout << "Concatenated C++ string: " << str3 <<endl;
    cout << "Copy String: " << str4 <<endl;
    cout << "Repetitions of a character: " << str5 <<endl;

    return 0;
}

Output

C++ string 1: Hello, World!
C++ string 2: Hello
Concatenated C++ string: Hello, C++!
Copy String: Hello, C++!
Repetitions of a character: AAAAA

 

Key Differences between C-Style and C++ Style Strings

Here’s a summary table that outlines the key differences between C-style strings and C++-style strings.

Aspect C-Style String C++-Style String (std::string)
Definition Array of characters ending with a null character ('\0'). Class from the C++ Standard Library.
Memory Management Manually managed, requiring careful handling of buffer sizes. Automatically managed by the std::string class.
Safety Prone to errors like buffer overflows and memory leaks. Safer, with automatic memory management and bounds checking.
Functionality Limited; requires using functions from the C library (strlen, strcpy, etc.). Rich set of built-in member functions (e.g., .length(), .substr(), .find()).
Ease of Use More complex, requires manual handling of memory and null terminators. Easier to use with high-level operations provided by the class.
Mutability Mutable, but changes need careful management of buffer sizes. Mutable and automatically manages resizing when needed.
Performance Generally faster in simple cases due to lower overhead but riskier. Slightly slower due to additional safety and flexibility, but often negligible in most cases.
Initialization Can be directly initialized with a string literal or manually character by character. Can be initialized with literals, another std::string, or various constructors.
Size Handling Size must be explicitly managed by the programmer. Size is automatically managed, with easy access to the length via .length() or .size().

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

5.0
5.0 out of 5 stars (based on 3 reviews)
Excellent100%
Very good0%
Average0%
Poor0%
Terrible0%

 

 

December 27, 2024

noiceeeeee

August 23, 2024

Very Very important.

August 23, 2024

great concepts

 

 

Submit a Review

 

 

Layer 1
Login Categories