Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,406 questions

56,397 answers

573 users

How to convert a string to an array of characters in C++

1 Answer

0 votes
/*
 * Converting a std::string to a character array in C++.
 *
 * In modern C++, a std::string already stores a sequence of characters.
 * However, some APIs or algorithms may require the characters in a
 * separate container such as std::vector<char>.
 *
 * This example demonstrates:
 *   - A dedicated conversion function
 *   - Const-correctness
 *   - Safe memory management via standard library containers
 *   - Clear documentation and error-free resource handling
 */

#include <iostream>
#include <string>
#include <vector>

/*
 * Converts a std::string into a std::vector<char>.
 *
 * Parameters:
 *   text - The source string.
 *
 * Returns:
 *   A vector containing each character from the string.
 *
 * Implementation note:
 *   The vector constructor accepts a range defined by iterators.
 *   This efficiently copies all characters from the string into
 *   the resulting vector.
 */
std::vector<char> stringToCharArray(const std::string& text)
{
    return std::vector<char>(text.begin(), text.end());
}

int main()
{
    const std::string text = "Hello, World!";

    // Convert the string to a character array representation.
    const std::vector<char> characters = stringToCharArray(text);

    std::cout << "Original string: " << text << '\n';

    std::cout << "\nCharacter array contents:\n";
    for (std::size_t i = 0; i < characters.size(); ++i) {
        std::cout << "characters[" << i << "] = '"
                  << characters[i] << "'\n";
    }
}


/*
run:

Original string: Hello, World!

Character array contents:
characters[0] = 'H'
characters[1] = 'e'
characters[2] = 'l'
characters[3] = 'l'
characters[4] = 'o'
characters[5] = ','
characters[6] = ' '
characters[7] = 'W'
characters[8] = 'o'
characters[9] = 'r'
characters[10] = 'l'
characters[11] = 'd'
characters[12] = '!'

*/
    

 



answered 2 days ago by avibootz
...