Calculate SMS Length/Parts C#

2020-07-29 23:55发布

问题:

I have been asked to help a friend in his application which has an indicator/counter that should show the end-user how many characters have been written in the text box and also how many parts in this written text/SMS?.

The easiest part was about getting the current characters count/length by using TextBox1.Text.Length, but the other part which was resposible for getting how many parts in this SMS text depending on both Arabic/Unicode and English/7Bit languages, and each language has a different specifications at GSM's side, as the one single Arabic message is 70 characters maximum and 67 for concatenated parts, and for English, it is 160 for the one single part and 153 for the concatenated parts.

回答1:

We had two options, the first one was that we were getting the SMS from the mobile operator with an encoding parameter which helped us to determine the language of the message if it was 7Bit or Unicode message, so it was easy to check the given encoding parameter value and go ahead with 160 or 70 check, and the other option was to have our own language checker. Anyways, we used the below code and it works perfectly:

public int CalculateSmsLength(string text)
{
    if (IsEnglishText(text))
    {
        return text.Length <= 160 ? 1 : Convert.ToInt32(Math.Ceiling(Convert.ToDouble(text.Length) / 153));
    }

    return text.Length <= 70 ? 1 : Convert.ToInt32(Math.Ceiling(Convert.ToDouble(text.Length) / 67));
}

public bool IsEnglishText(string text)
{
    return Regex.IsMatch(text, @"^[\u0000-\u007F]+$");
}

Math.Ceiling returns the smallest integer greater than or equal to the specified number.

P.S. We had an application was detecting the given text if it was in 7Bit or Unicode encoding, but it is a long code and will post it later under an appropriate title.