簡單的東東,什麼也不說了,上代碼。
View Code
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
public partial class GetPrintContent : System.Web.UI.Page
{
protected string ClientCode = string.Empty;
protected string LogoTxt = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request["Str"]))
{
StringBuilder xmlString = new StringBuilder();
this.ClientCode = "勝多負少勝多負少勝多負少勝多負少12345勝多負少勝多負少勝多負少勝多負少12345勝多負少";
xmlString.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
xmlString.AppendLine("<PRINT>");
xmlString.AppendLine("<LOGO URI=\"中英文混合字符串截取固定長度\"/>");
string logoTxt = this.ClientCode.Replace("\r\n", "");
if ((logoTxt.Length / 16 + 1) > 1)
{
int startIndex = 0;//字節數www.2cto.com
int subLen = 16;
int subCount = logoTxt.Length / 16 + 1;
for (int i = 0; i < subCount; i++)
{
string oneOfVal = SubStrLenth(logoTxt, startIndex, subLen * 2);
if (oneOfVal != "")
{
xmlString.AppendLine("<TEXT VAL=\"" + oneOfVal + "\"/>");
startIndex += GetStrByteLength(oneOfVal);
}
else
{
break;
}
}
}
else
{
xmlString.AppendLine("<TEXT VAL=\"" + logoTxt + "\"/>");
}
xmlString.AppendLine("</PRINT>");
Response.ContentEncoding = Encoding.UTF8;
Response.ContentType = "text/xml";
Response.Charset = "utf-8";
Response.Write(xmlString);
Response.End();
//}
}
}
private bool ISChinese(char C)
{
return (int)C >= 0x4E00 && (int)C <= 0x9FA5;
}
private int GetStrByteLength(string str)
{
return System.Text.Encoding.Default.GetByteCount(str);
}
private string SubStrLenth(string str, int startIndex, int length)
{
int strlen = GetStrByteLength(str);
if (startIndex + 1 > strlen)
{
return "";
}
int j = 0;//記錄遍歷的字節數
int L = 0;//記錄每次截取開始,遍歷到開始的字節位,才開始記字節數
int strW = 0;//字符寬度
bool b = false;//當每次截取時,遍歷到開始截取的位置才為true
string restr = string.Empty;
for (int i = 0; i < str.Length; i++)
{
char C = str[i];
if (ISChinese(C))
{
strW = 2;
}
else
{
strW = 1;
}
if ((L == length-1) && (L + strW > length))
{
b = false;
break;
}
if (j >= startIndex)
{
restr += C;
b = true;
}
j += strW;
if (b)
{
L += strW;
if (((L + 1) > length))
{
b = false;
break;
}
}
}
return restr;
}
}
希望有更簡潔方便的解決方案的同道,不吝賜教。