StringExtension.cs 2.42 KB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hh.Mes.Common
{
    public static class StringExtension
    {
        /// <summary>针对单个格式字符串调用 "welcome to {0}! welcome to {1}!".FormatWith("lsw", "wisdom"); 未做null判断
        /// </summary>
        public static string FormatWith(this string format, params object[] args)
        {
            var capacity = format.Length + args.Select(p => p.ToString()).Sum(p => p.Length);
            Console.WriteLine(capacity);
            var stringBuilder = new StringBuilder(capacity);
            stringBuilder.AppendFormat(format, args);
            return stringBuilder.ToString();
        }

        /// <summary>针对多个格式字符串 new string[] { "welcome to {0}!", " welcome to {1}!" }.FormatWith("lsw", "wisdom"); 
        /// </summary>
        public static string FormatWith(this IEnumerable<string> formats, params object[] args)
        {
            var capacity = formats.Where(f => !string.IsNullOrEmpty(f)).Sum(f => f.Length) +
                                args.Where(a => a != null).Select(p => p.ToString()).Sum(p => p.Length);
            var stringBuilder = new StringBuilder(capacity);
            foreach (var f in formats)
            {
                if (!string.IsNullOrEmpty(f))
                {
                    stringBuilder.AppendFormat(f, args);
                }
            }
            return stringBuilder.ToString();
        }


        /// <summary>
        ///  字符 特殊符号替换
        /// </summary>
        public static string StrJsonReplace(this string str)
        {
            var sb = new StringBuilder();
            for (int i = 0; i < str.Length; i++)
            {
                var c = str[i];
                switch (c)
                {
                    case '\"':
                    case '\'':
                    case '\\':
                    case '/':
                    case '\b':
                    case '\f':
                    case '\n':
                    case '\r':
                    case '\t':
                        sb.Append(" ");
                        break;
                    default:
                        sb.Append(c);
                        break;
                }
            }
            return sb.ToString().Replace("CNOOCLegLineUAT", " ").Replace("SqlSugar", "xxx").Replace("Sugar", "xxx").Replace("Sql", "xxx");
        }
    }
}