在 C# 中将字符串拆分为列表
Muhammad Maisam Abbas
2024年2月16日

本教程将讨论在 C# 中将字符串变量拆分为字符串列表的方法。
在 C# 中使用 String.Split()
方法将字符串变量拆分为字符串列表
String.Split()
方法根据 C# 中的给定分隔符拆分字符串变量。String.Split()
将主字符串拆分为多个子字符串,并以字符串数组的形式返回它们。可以使用 C# 中 Linq 的 ToList()
函数将 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
列表。
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
- C# 将字符串转换为枚举类型
- C# 中将整形 Int 转换为字符串 String
- 在 C# 中的 Switch 语句中使用字符串
- 如何在 C# 中把一个字符串转换为布尔值
- 如何在 C# 中把一个字符串转换为浮点数
- 如何在 C# 中编写多行字符串文字