Reputation: 341
I have a list of countries in a string format like this:
123 USA, America
126 South Africa, Africa
I want to split country code, country name and continent and save it in a list or array. Country code will have index[0], country name[1] and continent[2] in that order.
I tried this:
string number = "123 USA, America";
string[] numbers = number.Split(',');
But that only split the string into two: "123 USA" and "America", I want to be able to get the number part separate as well
Upvotes: 1
Views: 5038
Reputation: 3649
Try this:
public class Country
{
public int Number { get; set; }
public string Name { get; set; }
public string Continent { get; set; }
public static List<Country> Parse(string[] objects)
{
List<Country> countries = new List<Country>();
foreach (string obj in objects)
{
try
{
string[] tokens = obj.Split(',');
string[] first_portion_tokens = tokens[0].Split(' ');
countries.Add(new Country()
{
Number = int.Parse(first_portion_tokens[0]),
Name = string.Join(" ", first_portion_tokens.Skip(1).ToArray()),
Continent = tokens[1].Trim()
});
}
catch (System.Exception)
{
// invalid token
}
}
return countries;
}
}
and use it like this:
string[] myObjects = new string[] { "123 USA, America" , "126 South Africa, Africa" };
List<Country> countries = Country.Parse(myObjects);
Upvotes: 0
Reputation: 317
try using regular expressions
using System.Text.RegularExpressions
Regex rx = new Regex(@"?<=[0-9]",RegexOptions.Compiled | RegexOptions.IgnoreCase);
text = "your text here"
MatchCollection matches = rx.Matches(text); //matches is the numbers in your text
Upvotes: 0
Reputation: 2007
You can try like this
https://dotnetfiddle.net/uY021W
public static void Main()
{
string number = "123 USA, America";
string[] delimiters = {
@" ",
@","
};
var chunks = number.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for( int i=0;i< chunks.Count();i++)
{
Console.WriteLine(chunks[i]);
}
}
Upvotes: 0
Reputation: 37337
Try overload of Split
accepting array of char
/string
:
var splitted = number.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
Result is: string[3] { "123", "USA", "America" }
Upvotes: 1
Reputation: 520878
Try splitting on the following alternation:
(?<=[0-9]) |,
This says to split on either a space which is preceded by a digit, or a comma followed by a space.
Sample code:
string number = "123 USA, America";
string[] parts = Regex.Split(number, @"(?<=\d) |, ");
foreach (string part in parts)
{
Console.WriteLine(part);}
}
This prints:
123
USA
America
Upvotes: 3
Reputation: 17185
You can use IndexOf
to find the index of a specific character and then Substring
to separate that. I.e.
string number = "123 USA, America";
int index = number.IndexOf(' ');
string countryCode = number.Substring(0, index);
Be aware that this works only if the format of your strings is really consistent. If any of the strings did not have a country code, something wrong would happen.
Upvotes: 0