Split a string into multiple elements

Viewed 71

I need to split a string into multiple elements so that they can be inserted into an array. Below is an idea of what'd i'd like this to look like. The number of users is dynamic, but the string format never changes.

string Usernames = "User1, User2, User3, User4";
String[] Users = Usernames;
Console.WriteLine("First User: " + Usernames[0] + "Second User: " + Usernames[1]);
//output..
//First User: User1
//Second User: User2

3 Answers
var users = Usernames.Split(new string[] { ", " }, int.MaxValue, StringSplitOptions.None);

Here is another option

var users = Usernames.Split(new char[] {' ',','}, StringSplitOptions.RemoveEmptyEntries);

A. This is faster than splitting using new string[]{...}.

B. This is also resilient to missing ' 's, e.g. string Usernames = "User1,User2, User3,User4";

  string Usernames = "User1, User2, User3, User4";

  string[] users = Usernames.Split(',');

  var userVariable = users.Select(usr=> usr.Trim()).ToArray();

  Console.WriteLine("First User: " + userVariable[0] + "Second User: " + userVariable[1]);
Related