分割字符串并知道结果的相对位置

时间:2019-04-24 11:44:31

标签: c#

具有一个字符串,例如:

string foo = "10::12"

如何拆分字符串,但仍保留结果的位置?

为澄清起见,foo是动态的,在给定时间内字符串可能只是::12。使用简单的拆分,我不知道所得的12是在分隔符的左侧还是右侧。

谢谢!

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

public static void Main()
    {
        ParseAndPrint("::12");
        ParseAndPrint("10::12");

    }

      private static void ParseAndPrint(string input)
        {
            string[] parts = input.Split(new[] {"::"}, StringSplitOptions.None);
            var left = parts[0];
            var right = parts[1];

            Console.WriteLine("L:" + left + " R:" + right);
        }

https://dotnetfiddle.net/rHw07f

答案 1 :(得分:1)

如果使用正则表达式查找所有数字,则可以使用Index类的Match属性来查找数字和该数字的索引。

Regex regex = new Regex(@"\d+");

foreach (Match match in regex.Matches("10::12"))
{
    Console.WriteLine($"{match.Index}, {match.Value}");
}

输出:

  

0,10
  4、12