Convert char[] to string [Digg.com This!]
char[] is quite convenient if you're reading file data using StreamReader, but it doesn't offer the same functionality as string does. Here's one way I've found of converting:
char[] charBuf = new char[1024]; // Example char array
string s = ""; // Example empty string
s = new string(charBuf); // Create new string passing charBuf into the constructor



4 Comments:
Thanks Paul,
I found this tip near the top of the list when doing a google search. Works like a champ.
Richard
No!
new string(charBuf) returns a string* but s is not a string*!
And if it was, who will free it's memory?
To convert a char* to a string you may use :
s.insert(0, charBuf);
And if you are not sure that s is empty, use s.clear() before.
Works beautifully. Thanks for the tip Paul!
Pierre, it's C# not C++ :)
Post a Comment
<< Home