I want to convert few strings, ex:
to array of characters, ex:Code:string1 = "abc";
string2 = "123";
How can I do this?Quote:
char1[0] = 'a';
char1[1] = 'b';
char1[2] = 'c';
char2[0] = '1';
char2[1] = '2';
char2[2] = '3';
Printable View
I want to convert few strings, ex:
to array of characters, ex:Code:string1 = "abc";
string2 = "123";
How can I do this?Quote:
char1[0] = 'a';
char1[1] = 'b';
char1[2] = 'c';
char2[0] = '1';
char2[1] = '2';
char2[2] = '3';
char foo[10];
strcpy( foo, string.c_str() );
This code avoids overruns in the case where the string isnt properly termianted with a NULLCode:BYTE Foo[10];
DWORD Index = 0;
while((string1[Index] !=0) && (Index < 10)){
CopyMemory(&Foo[Index] , &string1[Index] , 1);
Index++;
}
No, actually, it doesn't. If the string is 3 characters long, but doesn't have a NULL terminator, you just keep copying. And your code acts like strncpy(): if the string is longer than 10 characters, you don't add a terminator to it.
And to top it off, that code is Windows-only. Why do it unportably if you can do it portably? At the very least, mention that it is Windows-specific, especially when the OP said nothing about Windows programming.
And why use a range copy call when the = has the same semantics? For PODs, this:
CopyMemory(&Foo[Index] , &string1[Index] , 1);
is the same as
Foo[Index] = string1[Index];
except slower, more complicated, less readable and more error-prone.
To get a mutable C-style array of characters, I'd use this:
Code:std::vector<char> v(string1.begin(), string1.end());
FunctionThatWantsCharPtr(&v[0], v.size());