【问题标题】:How to split numbers from string in C#如何在C#中从字符串中拆分数字
【发布时间】:2020-03-19 05:01:30
【问题描述】:

我有一个这样的字符串格式的国家/地区列表:

123 USA, America
126 South Africa, Africa

我想拆分国家代码、国家名称和大陆并将其保存在列表或数组中。国家代码将依次具有索引[0]、国家名称[1]和大陆[2]。

我试过这个:

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

但这只是将字符串分成两部分:“123 USA”和“America”,我也希望能够将数字部分分开

【问题讨论】:

标签: c#


【解决方案1】:

尝试按以下交替进行拆分:

(?<=[0-9]) |, 

这表示在前面有数字的空格或逗号后面跟着空格的地方分割。

示例代码:

string number = "123 USA, America";
string[] parts = Regex.Split(number, @"(?<=\d) |, ");
foreach (string part in parts)
{
    Console.WriteLine(part);}
}

打印出来:

123
USA
America

【讨论】:

  • @mypronounismonicareinstate 因为有时分割的分隔符只是一个空格,有时是逗号后跟一个空格。我的回答没有什么“丑陋”的地方。
【解决方案2】:

您可以使用IndexOf 查找特定字符的索引,然后使用Substring 将其分开。即

string number = "123 USA, America";
int index = number.IndexOf(' ');
string countryCode = number.Substring(0, index);

请注意,这仅在您的字符串格式真正一致时才有效。如果任何字符串没有国家代码,就会发生错误。

【讨论】:

    【解决方案3】:

    尝试重载Split 接受char/string 的数组:

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

    结果是:string[3] { "123", "USA", "America" }

    【讨论】:

    • @UwakPeter 仅当字符串格式为 - “{number} {Country}, {Continent}”时才能使用此选项
    【解决方案4】:

    你可以这样试试

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

    【讨论】:

      【解决方案5】:

      试试这个:

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

      并像这样使用它:

          string[] myObjects = new string[] { "123 USA, America" , "126 South Africa, Africa" };
          List<Country> countries = Country.Parse(myObjects);
      

      【讨论】:

        【解决方案6】:

        尝试使用正则表达式

        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-15
          • 2020-12-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多