• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

网络口袋

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

[C#]函数 格式化字符串到指定长度

Code
    /// <summary>
    
/// 格式化字符串到指定长度
    
/// </summary>
    
/// <param name="str"></param>
    
/// <param name="length"></param>
    
/// <returns></returns>
    public static string Format(string str, int length)
    {
        
if (str == null)
            
return "暂无数据";
        
string s = str.Trim();
        
if (s.Length == 0)
            
return "暂无数据";
        
byte[] b = System.Text.Encoding.Default.GetBytes(s);
        
if (b.Length > length)
        {
            
string t = System.Text.Encoding.Default.GetString(b, 0, length);
            
if (t[t.Length-1] != s[t.Length-1])
                
return System.Text.Encoding.Default.GetString(b, 0, length - 1) + "";
            
else
                
return t + "";
        }
        
else
        {
            
return s;
        }
    }

posted on 2009-10-27 16:30  俊  阅读(1241)  评论(2)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3