-2

I wish to know how to calculate the size of string data type. says what is the size of s under the following scenario?

string s="";
string s="1";
string s="12";

If possible, can point to a website mentioned this?

DIF
  • 2,470
  • 6
  • 35
  • 49
pullinssfaulk
  • 23
  • 1
  • 1
  • 4
  • 11
    Define "size"? Number of characters? Number of unicode points? (this is not necessarily the same) Number of bytes under a yet-to-be-specified encoding? Number of pixels? Number of millimetres? Number of bytes comprising the `string` instance? – Marc Gravell Apr 23 '14 at 12:48
  • 1
    If you're asking about the number of characters, then I think you should get yourself a c# book and read it before posting anything on the internet, because those are the absolute basics. – Tarec Apr 23 '14 at 13:08

4 Answers4

6

Refer to this link: How to know the size of the string in bytes?

System.Text.Encoding.Unicode.GetByteCount(s);
System.Text.Encoding.ASCII.GetByteCount(s);

or from msdn: http://msdn.microsoft.com/en-us/library/system.string.aspx

Community
  • 1
  • 1
Snake Eyes
  • 16,287
  • 34
  • 113
  • 221
  • Right. Just want to point out, that he will have to use the encoding according to the string he has :) – Boas Enkler Apr 23 '14 at 12:51
  • @BoasEnkler: What do you mean by that? A string in .NET doesn't *have* any idea of an encoding; or rather, the "native" representation is always UTF-16. It's not like there's such a thing as a "UTF-8 string". – Jon Skeet Apr 23 '14 at 12:53
  • Yes your right. I mixed up the fact that in files he could have diffenrent encodnings, but reading them in .net. would again end in UTF-16. My mistake :) – Boas Enkler Apr 23 '14 at 12:55
5

It is not clear from your question what you meant.

If by size you mean how many characters, then Length is the property you are looking for

"".Length   // 0
"1".Length  // 1
"12".Length // 2

If by size you mean how many bytes then this is dependant on encoding and you can use the answer Snake Eyes has given

Encoding.Unicode.GetByteCount("")   // 0
Encoding.UTF8.GetByteCount("")      // 0

Encoding.Unicode.GetByteCount("1")  // 2
Encoding.UTF8.GetByteCount("1")     // 1

Encoding.Unicode.GetByteCount("12") // 4
Encoding.UTF8.GetByteCount("12")    // 2

If by size you mean value of the number then you will need to parse the text

Int32.Parse("")   // FormatException: Input string was not in a correct format
Int32.Parse("1")  // 1
Int32.Parse("12") // 12
dav_i
  • 27,509
  • 17
  • 104
  • 136
0

please use the code below

long size=sizeof(char) *s.length; 
0

LMGTFY

Anything and everything string http://msdn.microsoft.com/en-us/library/system.string.aspx

String Length http://msdn.microsoft.com/en-us/library/system.string.length.aspx

String number of bytes (and string to byte array is covered in examples) http://msdn.microsoft.com/en-us/library/w3739zdy(v=vs.110).aspx

tdbeckett
  • 618
  • 8
  • 19