C# int數組轉string字符串


方式一:通過循環數組拼接的方式;

 int[] types = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 string result = string.Empty;
 for (int i = 0; i < types.Length; i++)
 {
      result += types[i];
      if (i < types.Length - 1)
            result += ",";
 }
 MessageBox.Show(result);

方式二:使用string 對象中Join方法實現;

 int[] types = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 string result = string.Join(",", types);
 MessageBox.Show(result);

根據上述的兩種方式,可以看到使用第二種代碼相對簡潔了很多;

C# 中 String. Join 方法 是 連接指定數組的元素或集合的成員,在每個元素或成員之間使用指定的分隔符。

Join方法還有好幾個重載方法,如下圖:

  可以根據不同的轉換需求去使用,在此就不舉例了。

  那么,兩種方法的效率那個更高一些呢?來個簡單的測試

  

int[] types = new int[10000];
            for (int i = 0; i < 10000; i++)
            {
                types[i] = i;
            }
            DateTime start = DateTime.Now;
            //方法1
            string result = string.Empty;
            for (int i = 0; i < types.Length; i++)
            {
                result += types[i];
                if (i < types.Length - 1)
                    result += ",";
            }
            //方法二
            //string result = string.Join(",", types);    

            DateTime end = DateTime.Now;

            MessageBox.Show((end - start).TotalMilliseconds.ToString());        
View Code

 

  方法1和方法2每個方法分別運行10次,求個平均值:

方法類型 第1次 第2次 第3次 第4次 第5次 第6次 第7次 第8次 第9次 第10次 平均值(單位:毫秒)
方法1  259 161  150   169 157   151 159   200 143   163  171.2
方法2  12  2  2  1  1  0.9  1 2.9   2.78 

    通過上面的對比,可以看出方法2有絕對的優勢,並且代碼也比較簡潔,所以,在有Int數組轉換string字符串的需求的時候,推薦使用方法2

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM