|
-
November 29th, 2012, 01:50 AM
#2
Re: C# strings and char arrays
So, first of all don't use this pattern (null-terminated char arrays) unless there is a compelling need to (like communicating with a server that expects it or something).
However, there are two ways to do this:
The first (and easiest, I think) is to call .Trim(char) on the string like this:
Code:
char[] temp = new char[30]; // initialized as nulls '\0'
for(int z=0; z<10; z++)
temp[z] = '0'; // temp should be "0000000000"
string strout = new string(temp); // create string from array of 0's
strout = strout.TrimEnd('\0'); //Remove any trailing null characters from the string
strout += "12345"; // should now be "000000000012345"
Note though that in C#, strings are immutable. So calling strout = strout.TrimEnd('\0'); is actually giving you an entirely different string
Alternatively, you could calculate the index of the null-terminator first and pass it as a parameter to the string constructor like this:
Code:
char[] temp = new char[30]; // initialized as nulls '\0'
for(int z=0; z<10; z++)
temp[z] = '0'; // temp should be "0000000000"
int nullIndex = Array.IndexOf<char>(temp, '\0'); //Find the null terminator
//In case there there is no null terminator, consider the whole array to be useable data
if( nullIndex < 0 )
nullIndex = temp.Length;
string strout = new string(temp, 0, nullIndex); //Three parameters: the array, the start index, the length
strout += "12345"; // should now be "000000000012345"
Console.WriteLine(strout);
Here is the relevant MSDN link: http://msdn.microsoft.com/en-us/library/ms131424.aspx
Make sense?
Good luck with C#. Your C++ background should make it easy to learn the language. Hopefully you'll find that things are a little more convenient in C# simply because you can avoid a lot of low-level management with fairly expressive syntax.
Best Regards,
BioPhysEngr
http://blog.biophysengr.net
--
All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|