您的位置:首页 > 编程语言 > C#

C# 【String】 用法

2016-03-05 11:10 483 查看
0.【string.Replace】

string str = "中文";
str.Replace("中", "英");
Debug.Log(str);// 英文


1 .【string.Format】用法

string text1 = "1";
string text2 = "2";
string endString = "";

endString = string.Format("{0}/{1}", text1,text2);
Debug.Log(endString); // 1/2

endString = string.Format("{0}/h", text1);
Debug.Log(endString); // 1/h


2.【string.Split()】 分割字符串

以某个特定字符为分割线,把一个字符串可以分拆成若干个,存在数组里。

private void test()
{
string testWords = "我_9999_Happy";

string[] list = testWords.Split('_');

for (int i = 0; i < list.Length; i++)
{
list[0] = "我";
list[1] = "9999";
list[2] = "Happy";
}
}

以“ ,”分割成数组

// 60019,9,9,9  {60019,9,9,9}
public static List<string> SplitStringDouhao(string str)
{
<span style="white-space:pre">	</span>List<string> result = new List<string>();
if (string.IsNullOrEmpty(str))
{
return result;
}

string[] tmp = str.Split(',');
result.AddRange(tmp);
for (int i = result.Count - 1; i >= 0; i--) {
if(string.IsNullOrEmpty(result[i]))
{
result.RemoveAt(i);
}
}
return result;
}

6100001,10;6100002,10;6100003,10;6100004,10 拆分成data数组

public class ItemDataStruct
{
public int _Id;
public int _Num;

public ItemDataStruct(int id, int num)
{
_Id = id;
_Num = num;
}
}

public class ConfigDataTool
{
static Dictionary<string, List<ItemDataStruct>> _ItemDatas = new Dictionary<string, List<ItemDataStruct>>();
// 6100001,10;6100002,10;6100003,10;6100004,10
public static List<ItemDataStruct> GetItemDataStruct(string str)
{
// 计算md5缓存中是否存在
string md5 = ClientTools.GetMD5(System.Text.Encoding.UTF8.GetBytes(str));
if (_ItemDatas.ContainsKey(md5))
{
return _ItemDatas[md5];
}

List<ItemDataStruct> list = new List<ItemDataStruct>();
if(str.Contains(",") == false)
{
return list;
}
string[] items = str.Split(';');
for (int i = 0; i < items.Length; i = i + 1)
{
if(string.IsNullOrEmpty(items[i]))
{
continue;
}
string[] item = items[i].Split(',');
if (item.Length == 2)
{
ItemDataStruct data = new ItemDataStruct(int.Parse(item[0]), int.Parse(item[1]));
list.Add(data);
}
else
{
Debug.LogError(" data error");
}
}
if(list.Count == 0)
{
return list;
}
_ItemDatas.Add(md5, list);
return list;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: