想问一个字符串输出的问题
假设有这么一个string words=“关于朝核问题:双方一致认为,朝鲜半岛核问题只能在六方会谈框架内通过政治外交方式解决,重申愿相互并同六方会谈其他各方继续密切协作,在恪守2005”,可以用什么方法,对他进行处理!形成类似下面的
关于朝核问题:双方一致认为,朝鲜半岛核问题只能在六方会谈框架内通过政治外交方式解决,重申愿相互并同六方会谈其他各方继续密切协
作,在恪守2005
总之让后面的字符,不要顶格输出!
2011-06-17 14:54
2011-06-18 08:58
2011-06-19 21:48
程序代码: /// <summary>
/// 格式化字符串
/// </summary>
/// <param name="str">要处理的字符串</param>
/// <param name="control">输出控件</param>
/// <returns></returns>
public string FormatStr(string str, System.Windows.Forms.Control control)
{
try
{
if (string.IsNullOrEmpty(str))
{
return str;
}
if (!str.Contains(":"))
{
return str;
}
string leftStr = str.Substring(0, str.IndexOf(':') + 1);
Graphics g = control.CreateGraphics();
Font font = control.Font;
int leftWidth = (int)g.MeasureString(leftStr, font).Width;
if (leftWidth > control.Width)
{
return str;
}
int RigthWidth = control.Width - leftWidth;
string otherStr = str.Substring(str.IndexOf(':') + 1);
int nowindex = 0;
int startindex = 0;
int lastindex = 0;
List<string> strlist = new List<string>();
while (nowindex < otherStr.Length)
{
if (g.MeasureString(otherStr.Substring(startindex, nowindex - startindex), font).Width + g.MeasureString("一", font).Width / 2 > RigthWidth)
{
strlist.Add(otherStr.Substring(startindex, nowindex - startindex) + "\r\n");
startindex = nowindex;
lastindex = nowindex;
nowindex--;
}
nowindex++;
}
strlist.Add(otherStr.Substring(lastindex));
string resultStr = leftStr;
string emptyStr = "";
while (emptyStr.Length < leftStr.Length)
{
emptyStr += " ";
}
if (strlist.Count > 0)
{
resultStr += strlist[0];
for (int i = 1; i < strlist.Count; i++)
{
resultStr += emptyStr + strlist[i];
}
}
return resultStr;
}
catch
{
throw new Exception("格式化字符串错误.");
}
}

2011-06-20 10:10