How to copy a specific contents of a char array to a string variable

Dear folk,

using win32 C++, I am looking for a function that can copy a specific number of charactes (starting from a specific index), of an char array to a string variable.

a code snippet as follows:

{

char charArray[255];

string stringVariable;

//copy a substring from charArray[12] to charArray[25] into string.

}

I wonder if there is such a string function that can help me to achieve my requirment.

Regards

Bassam



Answer this question

How to copy a specific contents of a char array to a string variable

  • Prasenna

    There are many ways:

    stringVariable = std::string(&charArray[12], &charArray[25]);

    or

    stingVariable.resize(13);

    memcpy(&stringVariable[0], &charArray[12], 13);

    etc. etc.



  • kevinwebster83

    Probably assign is appropriate too:

    stringVariable.assign(charArray + 12, charArray + 25 + 1);

    If charArray[25] must be excluded, then remove above "+ 1".


  • RANGERAZIZ

    You can make use of strncpy function
    The link also contains the sample code


  • Degremont

    Marius Bancila wrote:
    There are many ways:
    Yes, there are many ways; another possibility is:

    stringVariable = std::string(charArray+12, 14);



  • How to copy a specific contents of a char array to a string variable