简体   繁体   中英

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?

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:

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

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


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

Another Idea is to use Regex

The following regex should work: (?<=; )(.*?)(?=\s*\?>)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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