Click here to Skip to main content
15,912,329 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a list of countries in a string format like this:

123 USA, America
126 South Africa, Africa

i want to be able to split country code, country name and continent and save in a list or array, country code will have index[0], country name[1] and continent[2] in that order.

I have tried this:

What I have tried:

string number = "123 USA, America";
 string[] numbers = number.Split(',');





that only split the string into two: "123 USA" and "America", i want to be able to get the number part as well.
Posted
Updated 22-Nov-19 22:52pm
v2

You can also use a regular expression to get the different parts:
C#
using System.Text.RegularExpressions;
// ...
const string pattern = @"^(?<number>\d+)\s*(?<country>[^,]+),\s*(?<continent>[^,]+)$";

string test1 = "123 USA, America";
string test2 = "126 South Africa, Africa";

Regex r = new Regex(pattern, RegexOptions.Compiled);

Match m = r.Match(test1);
int number = int.Parse(m.Groups["number"].Value); // 123
string country = m.Groups["country"].Value; // USA
string continent = m.Groups["continent"].Value; // America

m = r.Match(test2);
number = int.Parse(m.Groups["number"].Value); // 126
country = m.Groups["country"].Value; // South Africa
continent = m.Groups["continent"].Value; // Africa
 
Share this answer
 
v2
Comments
Uwakpeter 26-Nov-19 3:15am    
Thanks Phil.o, it works.
Try:
C#
    string number = "123 USA, America";
    string[] numbers = number.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
...
private char[] splitChars = " ,".ToArray();
 
Share this answer
 
using System.Linq;

	string test = " 123 abc";
	string nums = new String(test.Where(Char.IsDigit).ToArray());
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900