
Patrick B. answered 07/23/20
Math and computer tutor/teacher
This is the very reason why I never jumped ship to the C++ string class. You CANNOT change a specific character inside a String object. In General, you CANNOT manipulate the string at the byte level. You have to convert it to a C-style string that is null terminated.
fortunately the method c_str() will do just that.
So I would recommend using the following function:
inline void String2CharArray( std::string & Str, char * str)
{
strcpy(str,Str.c_str());
}
Note that you will have to get the size of the string and allocate a buffer
for the C-style string. You can then do what you want with the C-style string
without changing the original std::string
Here is an example of what I am talking about:
//=========================================================
using namespace std;
#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
inline void String2CharArray( std::string & Str, char * str)
{
strcpy( str, Str.c_str());
}
int main()
{
string str="HE SAID HELLO";
int strLen = str.length();
char * strBuff = (char *) malloc(strLen+1); //allows for null terminator
String2CharArray( str, strBuff);
cout << str << endl; // HE SAID HELLO
cout << strBuff << endl; // HE SAID HELLO
//changes occur here.....
strBuff[0]='M';
strBuff[8]='J';
memcpy( &strBuff[3], (char*)"LIKE", 4 ); // typecast prevents the compiler warning
cout <<"-----------------------------------" << endl;
cout << str << endl; // HE SAID HELLO
cout << strBuff << endl; // ME LIKE JELLO
free(strBuff);
}
I would recommend familiarizing yourself with the functions in string.h
and stdlib.h
Otherwise you will have to hope that the great leaders of C++ will create
methods for manipulating string objects at the byte level...
I am not holding my breath, nor am I jumping ship.
I guess I'm just too old-fashioned and too old-school...
Oh well, cheers!