Convert strings to the RTF format-the RTF Research Series

Source: Internet
Author: User

As a result of the project, I have made in-depth research on the RTF format. Some of my experiences are shared with the source code!

Platform and language: VS2005, C #
/// <Summary>
/// Convert string to the RTF type
/// </Summary>
/// <Param name = "strs"> </param>
/// <Returns> </returns>
Public static string Str2RTF (string strs)
{
String tmpStr = "", tmpStr2 = "", strToRTF = "";
Int lstrLen = strs. Length;
If (lstrLen = 0)
Return "";
Foreach (Char c in strs)
{
TmpStr = c. ToString ();
Int tmpAsc = (int) c;
If (tmpAsc> 126) // convert the text in non-ASCII range to the RTF Format
{
TmpStr = CharTo16 (c );
If (tmpStr. Length = 1)
TmpStr = @ "\ '0" + tmpStr; // convert a special control symbol whose hex value is less than two digits
Else if (tmpStr. Length = 2)
TmpStr = @ "\ '" + tmpStr; // converts a special symbol whose hex value is equal to two digits.
Else
{
TmpStr2 = tmpStr. Substring (tmpStr. Length-2, 2); // Right (tmpStr, 2 );
TmpStr = tmpStr. Substring (0, 2); // Left (tmpStr, 2 );
TmpStr = @ "\ '" + tmpStr + @ "\'" + tmpStr2; // convert the hex value to a four-character non-English character internal code
}
}
// If (tmpStr = "\ '0d" | tmpStr = "\ '0a") // then' performs Special Control on line feed characters: 0D 0A
// TmpStr = @ "}{\ insrsid198535 \ par }{\ insrsid198535 \ loch \ af0 \ hich \ af0 \ dbch \ f13 ";

StrToRTF + = tmpStr;
}
Return strToRTF;
}


/// <Summary>
/// Convert Char to hexadecimal character
/// </Summary>
/// <Param name = "ch"> </param>
/// <Returns> </returns>
Public static string CharTo16 (char ch)
{
System. Text. Encoding chs = System. Text. Encoding. GetEncoding ("gb2312 ");
Byte [] bytes = chs. GetBytes (ch. ToString ());
String str = "";
For (int I = 0; I <bytes. Length; I ++)
{
Str + = string. Format ("{0: X2}", bytes [I]);
}
Return str. ToLower ();
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.