//-------------------------------------------------- // Motion Framework // Copyright©2018-2020 何冠峰 // Licensed under the MIT license //-------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; #if MOTION_SERVER using System.Numerics; #else using UnityEngine; #endif namespace MotionFramework.IO { public static class StringConvert { /// /// 正则表达式 /// private static Regex REGEX = new Regex(@"\{[-+]?[0-9]+\.?[0-9]*\}", RegexOptions.IgnoreCase); /// /// 替换掉字符串里的特殊字符 /// public static string ReplaceSpecialChar(string str) { return str.Replace("\\n", "\n").Replace("\\r", "'\r").Replace("\\t", "\t"); } /// /// 字符串转换为字符串 /// public static string StringToString(string str) { return str; } /// /// 字符串转换为BOOL /// public static bool StringToBool(string str) { int value = (int)Convert.ChangeType(str, typeof(int)); return value > 0; } /// /// 字符串转换为数值 /// public static T StringToValue(string str) { return (T)Convert.ChangeType(str, typeof(T)); } /// /// 字符串转换为数值列表 /// /// 分隔符 public static List StringToValueList(string str, char separator) { List result = new List(); if (!String.IsNullOrEmpty(str)) { string[] splits = str.Split(separator); foreach (string split in splits) { if (!String.IsNullOrEmpty(split)) { result.Add((T)Convert.ChangeType(split, typeof(T))); } } } return result; } /// /// 字符串转为字符串列表 /// public static List StringToStringList(string str, char separator) { List result = new List(); if (!String.IsNullOrEmpty(str)) { string[] splits = str.Split(separator); foreach (string split in splits) { if (!String.IsNullOrEmpty(split)) { result.Add(split); } } } return result; } /// /// 转换为枚举 /// 枚举索引转换为枚举类型 /// public static T IndexToEnum(string index) where T : IConvertible { int enumIndex = (int)Convert.ChangeType(index, typeof(int)); return IndexToEnum(enumIndex); } /// /// 转换为枚举 /// 枚举索引转换为枚举类型 /// public static T IndexToEnum(int index) where T : IConvertible { if (Enum.IsDefined(typeof(T), index) == false) { throw new ArgumentException($"Enum {typeof(T)} is not defined index {index}"); } return (T)Enum.ToObject(typeof(T), index); } /// /// 转换为枚举 /// 枚举名称转换为枚举类型 /// public static T NameToEnum(string name) { if (Enum.IsDefined(typeof(T), name) == false) { throw new ArgumentException($"Enum {typeof(T)} is not defined name {name}"); } return (T)Enum.Parse(typeof(T), name); } /// /// 字符串转换为参数列表 /// public static List StringToParams(string str) { List result = new List(); MatchCollection matches = REGEX.Matches(str); for (int i = 0; i < matches.Count; i++) { string value = matches[i].Value.Trim('{', '}'); result.Add(StringToValue(value)); } return result; } /// /// 字符串转换为向量 /// public static Vector3 StringToVector3(string str, char separator) { List values = StringToValueList(str, separator); return new Vector3(values[0], values[1], values[2]); } } }