在 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