简体   繁体   中英

How to split numbers from string in C#

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

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

Try overload of Split accepting array of char / string :

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

Result is: string[3] { "123", "USA", "America" }

You can use IndexOf to find the index of a specific character and then Substring to separate that. Ie

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.

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]);         
            }       
        }

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);

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

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