Ryan86
Ryan86

Reputation: 77

Asp.net String.Length counting return as 2 chars?

Im counting characters of a message from a textbox that will be sent as an sms, I've noticed that txtBody.Text.Length is counting more characters for returns, understand i want to keep the formatting of a newline but .net is counting 2 characters for this is there any way to keep the new line but get the counter to be accurate or is a return itself 2 characters ???

Upvotes: 3

Views: 3226

Answers (3)

Jon Hanna
Jon Hanna

Reputation: 113232

Textbox input will give you Environment.Newline whenever the user has input a new line (barring some relatively strange copy-pasting), which on windows is the same as "\u000D\u000A" (or the shorter "\r\n" which means the same thing).

For SMS sending you only really need to use U+000A.

Hence you can simply do msg.Replace("\r\n", "\n") before you do any further work. Not only will you get the Length result you want, but you cut down on wasted characters that SMSs don't need, and every char counts when it comes to SMS, hnce hrribl nnsens lik dis!

You might as well normalise further to msg.Replace("\r\n", "\n").Replace('\r', '\n\') to make more sense out of strange copy-pasted data with non-Windows-normal line-breaks (does happen in some scenarios).

Note that you're going to have more complications if you can't stay within the GSM 7-bit alphabet, though if you can't stay within the 8-bit either, then at least your complications will match between .NET and SMS; since .NET uses UTF-16 and SMS does when other encodings don't suffice, they treat surrogates the same as far as length goes.

Upvotes: 2

JP Hellemons
JP Hellemons

Reputation: 6047

string msg = "bla bla etc.\r\nSome more bla";
int length = msg.Replace("\r\n","").Length;

Upvotes: 0

Oded
Oded

Reputation: 498914

The newline in windows is indeed 2 characters - CrLf - ASCII 13 followed by ASCII 10.

You can simply decrement 2 from the returned Length, or get a count of all Environment.NewLine, double that by 2 and decrement from the Length.

Upvotes: 7

Related Questions