将字符串转换为列表 - C#
Convert String to List - c#
我有一个列表作为单个字符串,例如 - "['2','4','5','1']"
并且它的长度为 17,因为每个字符都被计算在内。
现在我想将它解析为列表对象,例如 - ['2','4','5','1']
其长度为 4 作为列表中元素的数量。
如何在 C# 中执行此操作?
不做基本的字符串操作可以吗?如果是那么怎么办?
尝试 Split
,
然后使用 Regex
只得到数字:
var str = "['2','4','5','1']".Split(new char[] {',' })
.Select(s => Regex.Match(s, @"\d+").Value);
或感谢@Fildor:
var str = Regex.Matches("['2','4','5','1']", @"\d+").Cast<Match>()
.Select(s=> s.Value);
您可以尝试 正则表达式 和 Linq 以便 Match
所有整数并将它们转换 (ToList()
) 到 List<int>
:
using System.Linq;
using System.Text.RegularExpressions;
...
string str = "['2','4','5','1']";
var result = Regex
.Matches(str, @"\-?[0-9]+") // \-? for negative numbers
.Cast<Match>()
.Select(match => int.Parse(match.Value)) // int.Parse if you want int, not string
.ToList();
Without basing string operations
您的字符串值看起来像有效的 JSON 数组。
using Newtonsoft.Json;
var list = JsonConvert.DeserializeObject<List<char>>("['2','4','5','1']");
// => ['2','4','5','1']
如果您需要输出为整数,请将输出类型设置为整数列表,JSON 序列化程序会将其转换为整数。
var list = JsonConvert.DeserializeObject<List<int>>("['2','4','5','1']");
// => [2, 4, 5, 1]
转换为整数也将处理负值 ;)
var list = JsonConvert.DeserializeObject<List<int>>("['-2','4','-5','1']");
// => [-2, 4, -5, 1]
我有一个列表作为单个字符串,例如 - "['2','4','5','1']"
并且它的长度为 17,因为每个字符都被计算在内。
现在我想将它解析为列表对象,例如 - ['2','4','5','1']
其长度为 4 作为列表中元素的数量。
如何在 C# 中执行此操作?
不做基本的字符串操作可以吗?如果是那么怎么办?
尝试 Split
,
然后使用 Regex
只得到数字:
var str = "['2','4','5','1']".Split(new char[] {',' })
.Select(s => Regex.Match(s, @"\d+").Value);
或感谢@Fildor:
var str = Regex.Matches("['2','4','5','1']", @"\d+").Cast<Match>()
.Select(s=> s.Value);
您可以尝试 正则表达式 和 Linq 以便 Match
所有整数并将它们转换 (ToList()
) 到 List<int>
:
using System.Linq;
using System.Text.RegularExpressions;
...
string str = "['2','4','5','1']";
var result = Regex
.Matches(str, @"\-?[0-9]+") // \-? for negative numbers
.Cast<Match>()
.Select(match => int.Parse(match.Value)) // int.Parse if you want int, not string
.ToList();
Without basing string operations
您的字符串值看起来像有效的 JSON 数组。
using Newtonsoft.Json;
var list = JsonConvert.DeserializeObject<List<char>>("['2','4','5','1']");
// => ['2','4','5','1']
如果您需要输出为整数,请将输出类型设置为整数列表,JSON 序列化程序会将其转换为整数。
var list = JsonConvert.DeserializeObject<List<int>>("['2','4','5','1']");
// => [2, 4, 5, 1]
转换为整数也将处理负值 ;)
var list = JsonConvert.DeserializeObject<List<int>>("['-2','4','-5','1']");
// => [-2, 4, -5, 1]