Thursday, March 16, 2006

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:

At 5:25 AM, Richard Bailey said...

Thanks Paul,

I found this tip near the top of the list when doing a google search. Works like a champ.

Richard

 
At 6:11 PM, Pierre said...

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.

 
At 7:35 PM, Baz said...

Works beautifully. Thanks for the tip Paul!

 
At 11:58 AM, findepi said...

Pierre, it's C# not C++ :)

 

Post a Comment

<< Home