简体   繁体   English

在 c# 中拆分大字符串并将其中的值添加到列表中

[英]Splitting large string in c# and adding values in it to a List

I have a string as shown below我有一个如下所示的字符串

string names = "<?startname; Max?><?startname; Alex?><?startname; Rudy?>";

is there any way I can split this string and add Max, Alex and Rudy into a separate list?有什么办法可以拆分此字符串并将 Max、Alex 和 Rudy 添加到单独的列表中?

Sure, split on two strings (all that consistently comes before, and all that consistently comes after) and specify that you want Split to remove the empties:当然,拆分两个字符串(所有始终在之前,所有始终在之后)并指定您希望 Split 删除空值:

var r = names.Split(new[]{ "<?startname; ", "?>" }, StringSplitOptions.RemoveEmptyEntries);

If you take out the RemoveEmptyEntries it will give you a more clear idea of how the splitting is working, but in essence without it you'd get your names interspersed with array entries that are empty strings because split found a delimiter (the <?... ) immediately following another (the ?> ) with an empty string between the delimiters如果您取出 RemoveEmptyEntries,它会让您更清楚地了解拆分是如何工作的,但本质上没有它,您的名字会散布在空字符串的数组条目中,因为 split 找到了一个分隔符( <?... ) 紧跟在另一个( ?> )之后,分隔符之间有一个空字符串

You can read the volumes of info about this form of split here - that's a direct link to netcore3.1, you can change your version in the table of contents - this variant of Split has been available since framework2.0您可以在此处阅读有关这种拆分形式的大量信息 - 这是 netcore3.1 的直接链接,您可以在目录中更改您的版本 - 这种拆分的变体从 framework2.0 开始可用


You did also say "add to a separate list" - didn't see any code for that so I guess you will either be happy to proceed with r here being "a separate list" (an array actually, but probably adequately equivalent and easy to convert with LINQ's ToList() if not) or if you have another list of names (that really is a List<string> ) then you can thatList.AddRange(r) it您确实还说“添加到单独的列表” - 没有看到任何代码,所以我想您要么很乐意继续使用r此处是“单独的列表”(实际上是一个数组,但可能足够等效且简单如果没有,则使用 LINQ 的 ToList() 进行转换,或者如果您有另一个名称列表(实际上是List<string> ),那么您可以thatList.AddRange(r)

Another Idea is to use Regex另一个想法是使用正则表达式

The following regex should work: (?<=; )(.*?)(?=\s*\?>)以下正则表达式应该可以工作: (?<=; )(.*?)(?=\s*\?>)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM