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);
}
///
/// 反斜杠替换为正斜杠
///
///
///
public static string ReplaceSlash(this string path)
{
return path.Replace("\\", "/");
}
///
/// 字节数组转16进制字符串
/// 每个字节转成两位的十六进制字符串
///
///
///
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;
}
///
/// 16进制字符串转字节数组
/// 谨慎使用
/// byte[].ToHexString()的逆向
///
///
///
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;
}
/////
///// 校验16进制字符串
/////
///// 16进制字符串
/////
//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;
//}
}
}