[c# tips] 加入分隔字元
之前有時會需要將陣列的字串資料轉成一串字串,然後以逗號(,)分隔,
常見於轉檔時的需求.
而通常也都用最直覺的方法用迴圈,如下:
string[] arr = new string[5];
//tmpStr = tmpStr.Substring(0, tmpStr.Length - 1);
arr[0] = "abc";
arr[1] = "def";
arr[2] = "ghi";
arr[3] = "jkl";
arr[4] = "mno";
string tmpStr = string.Empty;
foreach (string a in arr)
{
tmpStr += a + ",";
}
//改用TrimEnd清空最後一個分隔字元.
tmpStr = tmpStr.TrimEnd(',');
Console.WriteLine(tmpStr);
(用foreach先串完字串與分隔字元後,再將最後一個多的分隔字元移除.)
有時也會看到如下的寫法:
string[] arr = new string[5];
arr[0] = "abc";
arr[1] = "def";
arr[2] = "ghi";
arr[3] = "jkl";
arr[4] = "mno";
string tmpStr = string.Empty;
for (int i = 0; i < arr.Length; i++)
{
if (i != 0)
tmpStr += ",";
tmpStr += arr[i];
}
Console.WriteLine(tmpStr);
(用for迴圈跑,在字串前加分隔字元,但略掉第一個.)
後來才發現有個更好用的東西.
就是string.Join,用法如下:
string[] arr = new string[5];
arr[0] = "abc";
arr[1] = "def";
arr[2] = "ghi";
arr[3] = "jkl";
arr[4] = "mno";
string tmpStr = string.Join(",", arr);
Console.WriteLine(tmpStr);
這樣是不是簡潔多了呢!!
update@20090309:
感謝大估提供TrimeEnd的用法,又讓程式可以簡潔一點.