C# 字符串对齐
来源:互联网 发布:suse yast 安装软件 编辑:程序博客网 时间:2024/06/06 03:39
输出的字符串总是对不齐,于是写了个方法,在此记录下来,以备查看。
/// </summary>
/// <param name="str">输出字符串</param> /// <param name="len">字符串占用的字节长度</param> /// <returns></returns> public static string ToSameCharLength(string str, int len) { len = len + (len % 2); int singleChar = 0; int doubleChar = 0; int byteCount = 0; StringBuilder sb = new StringBuilder(); foreach (char c in str.Trim()) { sb.Append(c); byteCount = Encoding.Default.GetByteCount(c + ""); if (byteCount == 1) { singleChar++; } else if (byteCount == 2) { doubleChar++; } if (singleChar + 2 * doubleChar >len) { if (sb.Length>=1) { sb.Remove(sb.Length - 1, 1); } sb.Append("*"); break; }else if (singleChar + 2 * doubleChar==len) { break; } } str = sb.ToString(); singleChar = 0; doubleChar = 0; foreach (char c in str) { byteCount = Encoding.Default.GetByteCount(c + ""); if (byteCount == 1) { singleChar++; } else if (byteCount == 2) { doubleChar++; } } int count = len - singleChar - 2 * doubleChar; count = count < 0 ? 0 : count; return str + new string(' ', count); }
得到想要的整齐的输出:
0 0
- C# 字符串对齐
- C# string.format设置字符串宽度 对齐
- C#中英文混合字符串对齐输出
- 字符串对齐
- 字符串对齐
- C# String.Format 指定字符串宽度和对齐方式
- C# String.Format 指定字符串宽度和对齐方式
- C#中如何格式化对齐输出中英文混合字符串
- C#语言之“中英文混合字符串对齐”的方法【转】
- java字符串对齐方法
- Python - 字符串对齐
- python数字、字符串对齐
- 字符串对齐的方法
- 字符串左对齐
- 字符串 格式对齐
- 字符串输出对齐问题
- 字符串数组对齐问题
- C#中的内存对齐
- Android中如何模拟一次点击(touch)事件
- 如何在Excel的一列中查找重复的数据
- Javascript饼图和圆环图Pie & Donut for WPF
- 推荐阅读《JavaScript 语言精粹》
- 读者群体在国内IT领域应该算是比较大的
- C# 字符串对齐
- 花了几个小时JDBC连接sql server 2012出现的异常com.microsoft.sqlserver.jdbc.SQLServerException: 通过端口 1433 ...解决了!
- iOS开发-app被Rejected 的各种原因翻译
- CListCtrl 类中InsertItem, InsertColumn, SetItemText 的使用
- 拼音助记有什么用?
- how to replace html code to normal chars
- AD DNL&INL
- IEC61850变电站基本通信结构-原理和模型_3数据报告和记录
- linux2.6.30.4中dm9000网卡成功移植到TQ2440