How To Create A Fixed Length String In C# Mono


Recommended Posts

ok I need to create a fixed length string that is 31 char and a null

this is what I am trying

StringBuilder sb = new StringBuilder(name,31);

this.Name = sb.ToString();

Ideals or suiggestions..

how is this done in c++

Link to post
Share on other sites
ok I need to create a fixed length string that is 31 char and a null

How easily do you need the access the trailing null? If it's just for interop, I believe .NET strings are internally null-terminated so they can be passed to unmanaged code without marshalling.

StringBuilder sb = new StringBuilder(name,31);

this.Name = sb.ToString();

No idea if that's guaranteed to work. You probably have to set the StringBuilder's Capacity if you really 31 characters -- the ctor argument is a 'suggestion' -- but I'm not sure that's guaranteed to work, and I don't think there's any guarantee that the length of the string returned by ToString() will be the same as the StringBuilder's Capacity.

how is this done in c++

char s[32] = "foo"

;)

Edited by jcl
Link to post
Share on other sites

thanks,

stringbuild does infact shorten the string to the actual length when the ToString() method is used..

I did it this way

string FixedLength(string value)
{
if (string.lenght > 31)
{
string = string.substring(0,31);
string += "\zero";
}
else
(
string = value;
string += value.PadRight(31) + "\zero";
}

return string
}

EDIt:

Replace the word zero with the number 0, the BB keeps removing my 0 ..

Edited by iccaros
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...