Is there a way to tell the length of a UTF-8 encoded string in bytes in C #?

I wanted to see if there is a way to tell the size of the string file size in .NET. Imagine that you have a text sentence, and the host system should limit the size of the received text.

Is there a way to tell the size in bytes or KB of a string, or read only the first N bytes or KB of a UTF-8 encoded string?

string testSentence = "I only need the first 2 Kbytes of this sentence. Is it possible to break it into pieces of 2 KB sequences so that I can scroll and send 2 Kbytes to another process?"

+4
source share
3 answers

You can convert a string to bytes using Encoding.UTF8.GetBytes . Then divide the bytes into 2048 bytes. Be careful not to split one character into two pieces.

 byte[] bytes = Encoding.UTF8.GetBytes(testSentence); int pos = 0; int length = bytes.Length; while (length > 0) { int count = 2048; if (count >= length) // last chunk { // send chunk Send(bytes, pos, length); pos += length; length -= length; } else // not last chunk { // chop off last character while ((bytes[pos + count - 1] & 0xC0) == 0x80) count--; count--; // send chunk Send(bytes, pos, count); pos += count; length -= count; } } 

(unverified)

+3
source

Use the System.Text.Encoding.UTF8.GetByteCount () method.

(edited answer.)

0
source

I think something similar to the following will provide what you are looking for.

 byte[] data = System.Text.Encoding.UTF8.GetBytes(theString).Take(2048).ToArray(); 

or

 byte[] source = System.Text.Encoding.UTF8.GetBytes(theString); byte[] destination = new byte[2048]; Buffer.BlockCopy(source, 0, destination, 0, 2048); 

Edit: added example comment ..

This will provide you with List<byte[]> 2KB pieces, it is worth noting that this is not written for efficiency, but rather as an example, although it will perform a task that is not configured for high performance.

 string theString = new string('*', 1022574); byte[] allData = System.Text.Encoding.UTF8.GetBytes(theString); int numberOfChunks = (int)Math.Ceiling((double)(allData.Length) / 2048); List<byte[]> chunks = new List<byte[]>(numberOfChunks); for (int i = 0; i < numberOfChunks; i++) { chunks.Add(allData.Skip(i * 2048).Take(2048).ToArray()); } 
0
source

All Articles