【问题标题】:Getting two numbers which are separated by colon获取两个用冒号分隔的数字
【发布时间】:2016-04-29 20:23:11
【问题描述】:

我遇到了一些问题。我正在尝试拆分一些文本和数字。

考虑到这个字符串输入。

string input = "1 Johannes 1:3, 2 Johannes 2:6, 1 Mosebok 5:4";

我正在尝试将 2:3、2:6、5:4 与文本的其余部分分开。 然后我希望它们与冒号分开,并添加到列表中。

循环出来后,列表将如下所示。 2 3 2 6 5 4

我可以在其中从 [0] 和 [1]、[2] 和 [3]、[4] 和 [5] 创建一个 Hashtable 条目。

感谢大家对此的反馈。

【问题讨论】:

  • 向我们展示您迄今为止所做的尝试以及您遇到的任何错误,我们会帮助您。不幸的是,StackOverflow 不是一个为我编写代码的网站。
  • 一个非常简单的关于“在 C# 中拆分字符串”的谷歌搜索将得到你的方法,将它与一个简单的逻辑结合起来,哇!
  • 解决方案需要有多具体?如果这是输入将始终采用的形式,您可以简单地找到冒号的位置,然后假设直接在后面和前面的字符是您需要获取的。但如果要大于个位数,那就另当别论了
  • [\d]:[\d] 正则表达式来拯救。使用正则表达式Match 方法。
  • 您可以根据“,”进行拆分,使用 LastIndexOf 搜索最后一个空格,然后根据“:”再次拆分。您的输入的结构如何?

标签: c# .net string split colon


【解决方案1】:

如果我正确理解你的问题,我会这样做

string input = "1 Johannes 1:3, 2 Johannes 2:6, 1 Mosebok 5:4";
var table = Regex.Matches(input, @"(\d+):(\d+)")
                .Cast<Match>()
                .ToLookup(m => m.Groups[1].Value, m => m.Groups[2].Value);

【讨论】:

    【解决方案2】:

    使用正则表达式

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string input = "1 Johannes 1:3, 2 Johannes 2:6, 1 Mosebok 5:4";
    
                string pattern = @"(?'index'\d+)\s+(?'name'\w+)\s+(?'para'\d+:\d+),?";
                MatchCollection matches = Regex.Matches(input, pattern);
                foreach (Match match in matches)
                {
                    Console.WriteLine("index : {0}, name : {1}, para : {2}",
                        match.Groups["index"],
                        match.Groups["name"],
                        match.Groups["para"]
                    );
                }
                Console.ReadLine();
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      这里有一些可以帮助你的代码。

              var input = "1 Johannes 1:3, 2 Johannes 2:6, 1 Mosebok 5:4";
              var nextIndex = 0;
              var currentIndex = 0;
              var numbers = new List<int>();
      
              do
              {
                  currentIndex = input.IndexOf(":", currentIndex + 1);
                  var leftNumber = Convert.ToInt32(input[currentIndex - 1].ToString());
                  var rightNumber = Convert.ToInt32(input[currentIndex + 1].ToString());
      
                  numbers.Add(leftNumber);
                  numbers.Add(rightNumber);
      
                  nextIndex = input.IndexOf(":", currentIndex + 1);
      
              } while (nextIndex != -1);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-05-29
        • 1970-01-01
        • 2017-12-11
        • 2022-07-19
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多