converting char[] to string

C

claire

I have a char[] that i convert to a string as follows
m_tHeader.m_sshortname is defined as char[8];

string result = new string(m_tHeader.m_sshortname);

The problem is that any '\0' chars in the array remain in the string and
it's not terminated properly.

Is there a nice way to trim these off (string.trim doesnt work) rather than
my very nasty code below

while((result.Length > 0)&&(result[result.Length - 1] == '\0'))

result = result.Remove(result.Length - 1,1);



thanks
 
K

Kevin Spencer

Hi claire,

Yes, the C# string does not use a null terminator. That is, a C# string may
contain null characters.

Depending on what you want to do with the contents of the string, there are
several things you can do.

First, you can always convert a C# string to a char* (pointer to an array of
char), in which the first null terminator becomes the end of the string. Of
course, this requires some unsafe code to do, but I mentioned it in case it
might come in handy at some point in the future.

Second, you can initialize the string by using IndexOf when initializing the
string:

string result = new string(Array.IndexOf(m_tHeader.m_sshortname, '0');

or if you have .Net 2.0:

string result = new string(Array.IndexOf<char>(m_tHeader.m_sshortname, '0');

This overload will truncate the string you get at the first null 0. Of
course, you may have to check to see for sure whether there *is* a null zero
in the string, to prevent the third argument from being -1:

int index = Array.IndexOf<char>(m_tHeader.m_sshortname, '0')
string result = new string(m_tHeader.m_sshortname, 0, (index < 0 ? 0 :
index))

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer

Presuming that God is "only an idea" -
Ideas exist.
Therefore, God exists.
 
J

Jon Skeet [C# MVP]

claire said:
I have a char[] that i convert to a string as follows
m_tHeader.m_sshortname is defined as char[8];

string result = new string(m_tHeader.m_sshortname);

The problem is that any '\0' chars in the array remain in the string and
it's not terminated properly.

Is there a nice way to trim these off (string.trim doesnt work)

Well, String.Trim does work - I suspect you're not using it properly.

Are you sure that the char array only has null characters at the end?
If so, just use:

string result = new string (m_tHeader.m_sshortname).TrimEnd('\0');

That should work fine (and does in my test code).

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top