How to convert a String to Array in C#

· 1 min read

Image we have a string: 123,456,78,789, we want to change it to an array, we can use the following code:

string szTmp="123,456,78,789";
string[] tmp = szTmp.Split(',');
 
for (int i = 0; i < tmp.Length; i++ )
        MessageBox.Show(tmp[i]);
 
// print out: 
// 123 
// 456
// 78
// 789

When the target string contains different separators such as: 123,456 78,789, Split support multiple separators as well:

string szTmp="123,456 78,789";
char[] char_tmp = { ',', ' '};
string[] tmp = szTmp.Split(char_tmp);
 
// print out: 
// 123 
// 456
// 78
// 789