12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- using System;
- namespace XGame.Framework.Utils
- {
- public static class StringUtils
- {
- public static string Format(this string format, params object[] args)
- {
- if (string.IsNullOrEmpty(format))
- {
- return string.Empty;
- }
- if (args == null || args.Length <= 0)
- return format;
- else
- return string.Format(format, args);
- }
- /// <summary>
- /// 反斜杠替换为正斜杠
- /// </summary>
- /// <param name="path"></param>
- /// <returns></returns>
- public static string ReplaceSlash(this string path)
- {
- return path.Replace("\\", "/");
- }
- /// <summary>
- /// 字节数组转16进制字符串
- /// 每个字节转成两位的十六进制字符串
- /// </summary>
- /// <param name="bytes"></param>
- /// <returns></returns>
- public static string ToHexString(this byte[] bytes)
- {
- var length = bytes?.Length ?? 0;
- if (length == 0)
- return string.Empty;
- var sb = StringBuilderUtils.Acquire();
- for (int i = 0; i < length; i++)
- {
- sb.Append(bytes[i].ToString("X2"));
- }
- var result = sb.ToString();
- StringBuilderUtils.Release(sb);
- Log.Debug($"ToHexString Length:{length} result Length:{result.Length} val:{result}");
- return result;
- }
- /// <summary>
- /// 16进制字符串转字节数组
- /// 谨慎使用
- /// byte[].ToHexString()的逆向
- /// </summary>
- /// <param name="hexString"></param>
- /// <returns></returns>
- public static byte[] ToHexBytes(this string hexString)
- {
- //#if UNITY_EDITOR || DEBUG
- // hexString = CheakHexString(hexString);
- //#endif
- // hexString = hexString.Replace(" ", "");
- byte[] bytes = new byte[hexString.Length / 2];
- for (int i = 0; i < bytes.Length; i++)
- bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
- return bytes;
- }
- ///// <summary>
- ///// 校验16进制字符串
- ///// </summary>
- ///// <param name="strBuffHex">16进制字符串</param>
- ///// <returns></returns>
- //private static string CheakHexString(string strBuffHex)
- //{
- // strBuffHex = strBuffHex.Trim(); //去除前后空字符
- // strBuffHex = strBuffHex.Replace(',', ' '); //去掉英文逗号
- // strBuffHex = strBuffHex.Replace(',', ' '); //去掉中文逗号
- // strBuffHex = strBuffHex.Replace("0x", ""); //去掉0x
- // strBuffHex = strBuffHex.Replace("0X", ""); //去掉0X
- // strBuffHex = Regex.Replace(Regex.Replace(strBuffHex, @"(?i)[^a-f\d\s]+", ""), "\\w{3,}", m => string.Join(" ", Regex.Split(m.Value, @"(?<=\G\w{2})(?!$)").Select(x => x.PadLeft(2, '0')).ToArray())).ToUpper();
- // return strBuffHex;
- //}
- }
- }
|