Sai A Sai A
Updated date Mar 15, 2024
In this blog, we will learn how to convert C-style strings to C++ strings with simple explanations and code examples. Explore multiple methods, including constructors and assignment operators.

Method 1: Using Constructors

To convert a C-style string to a C++ string is by using the constructor of std::string. This constructor accepts a const char* argument, which is exactly what a C-style string is. Let's see how this works in practice:

#include <iostream>
#include <string>

int main() {
    const char* cString = "Hello, World!";
    std::string cppString(cString);

    std::cout << "C++ String: " << cppString << std::endl;

    return 0;
}

Output:

C++ String: Hello, World!

In this method, we simply pass the C-style string cString as an argument to the constructor of std::string. The constructor then creates a new C++ string object with the content of the C-style string.

Method 2: Using Assignment Operator

To convert a C-style string to a C++ string is by using the assignment operator (=) of std::string. This operator allows us to assign a C-style string directly to a std::string object. Let's see an example:

#include <iostream>
#include <string>

int main() {
    const char* cString = "Hello, World!";
    std::string cppString;

    cppString = cString;

    std::cout << "C++ String: " << cppString << std::endl;

    return 0;
}

Output:

C++ String: Hello, World!

Here, we declare a std::string object cppString and then assign the value of the C-style string cString to it using the assignment operator (=). This effectively converts the C-style string to a C++ string.

Method 3: Using std::string Constructor with Length Specified

If we know the length of the C-style string, we can use a constructor of std::string that takes two arguments: a pointer to the character array and the length of the string. This method is useful when dealing with strings that contain null characters within them. Let's illustrate:

#include <iostream>
#include <string>

int main() {
    const char cString[] = {'H', 'e', 'l', 'l', 'o', '\0', 'W', 'o', 'r', 'l', 'd', '!', '\0'};
    int length = 5; // Length of the string "Hello"

    std::string cppString(cString, length);

    std::cout << "C++ String: " << cppString << std::endl;

    return 0;
}

Output:

C++ String: Hello

In this example, we specify the length of the C-style string (length) as 5, which corresponds to the characters before the null terminator. The std::string constructor then creates a C++ string with only those characters.

Comments (0)

There are no comments. Be the first to comment!!!