how to find out number of bytes in a string

  • Thread starter Thread starter joyce
  • Start date Start date
J

joyce

hi

How would I go abouts finding out how many bytes a string has. ( I
want to do this so that I can set the datatype on the database
approriately.)


Thanks
Joyce
 
Joyce,

For a database, why would you want to know how many bytes are in a
string? If anything, you should be doing this on a character basis. I
can't imagine a database that doesn't support unicode characters, which is
what .NET natively stores its strings as.
 
Hi,

you can try to do something like
UnicodeEncoding.Unicode.GetByteCount("abc");
 
How would I go abouts finding out how many bytes a string has. ( I
want to do this so that I can set the datatype on the database
approriately.)

Conceptually, a string doesn't have bytes, it has characters (which
you can find out with the Length property).

Now, a string can be *encoded* into a sequence of bytes, and you can
find out how many bytes would be involved for any particular encoding
using Encoding.GetByteCount(string).

Jon
 
For a database, why would you want to know how many bytes are in a
string? If anything, you should be doing this on a character basis. I
can't imagine a database that doesn't support unicode characters, which is
what .NET natively stores its strings as.

That doesn't mean it's the native storage of the database though. I
remember when I was coding against a Postgres database, it stored
character data in UTF-8 by default (on the platform I was running on).
Now an index could only take something like 2783 bytes per row, so I
had to truncate the string I was using to take only about 2700 bytes
*in UTF-8* without chopping it half way through a character or
anything like that.

Most amusing.

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

Back
Top