在 C# 中將字串拆分為列表

Muhammad Maisam Abbas 2024年2月16日
在 C# 中將字串拆分為列表

本教程將討論在 C# 中將字串變數拆分為字串列表的方法。

在 C# 中使用 String.Split() 方法將字串變數拆分為字串列表

String.Split() 方法根據 C# 中的給定分隔符拆分字串變數。String.Split() 將主字串拆分為多個子字串,並以字串陣列的形式返回它們。可以使用 C# 中 LinqToList() 函式String.Split() 方法返回的字串陣列轉換為列表。以下程式碼示例向我們展示瞭如何使用 C# 中的 String.Split()ToList() 函式基於分隔符將字串變數拆分為字串列表。

using System;
using System.Collections.Generic;
using System.Linq;

namespace split_string_to_list {
  class Program {
    static void Main(string[] args) {
      string split = "this, needs, to, split";
      List<string> list = new List<string>();
      list = split.Split(',').ToList();
      foreach (var l in list) {
        Console.WriteLine(l);
      }
    }
  }
}

輸出:

this
 needs
 to
 split

在上面的程式碼中,我們使用 split.Split(',') 函式基於分隔符拆分了字串變數 split。用 C# 中的 ToList() 函式將結果陣列轉換為字串 list 列表。

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

相關文章 - Csharp String

相關文章 - Csharp List