【问题标题】:First N Characters of a String until they are not digits字符串的前 N ​​个字符,直到它们不是数字
【发布时间】:2019-09-10 07:52:55
【问题描述】:

我有一个长字符串,例如以下两个字符串:

  1. 93434234adfjasdf asdfjksdfkl afjasdlfjl asdfjsdlkfjasdf ksdafjlaskdfjasdf
  2. 123asdjfklasdfj asdf asdfjlkasd jasdlfkja sdfj klasdjfkl asdflk asdfj

我知道字符串每次都以数字开头,但我不知道字符串中有多少个字符是数字。当然我可以做这样的事情:

string completeText = "93434234adfjasdf asdfjksdfkl afjasdlfjl asdfjsdlkfjasldf ksdafjlaskdfjasdf";
char[] charSequence = completeText.ToCharArray();
int counter = 0;
foreach (var charItem in charSequence)
{
    if (Char.IsDigit(charItem))
    {
        counter++;
    }
    else
    {
        //Leave loop
        break;
    }
}
string myDigitsAtTheBeginningOfTheString = completeText.Substring(0, counter);

有没有更流畅的方法来做到这一点?

【问题讨论】:

  • 顺便说一下,这个问题会在Code Review 上触发更好的答案。下次在那里发布工作代码。

标签: .net string sequence


【解决方案1】:

你可以使用TakeWhile:

只要指定条件为真,就从序列中返回元素,然后跳过其余元素。

using System;
using System.Linq;

public static void Main()
{
    var input = "93434234adfjasdf asdfjksdfkl afjasdlfjl asdfjsdlkfjasldf ksdafjlaskdfjasdf";
    Console.WriteLine(string.Concat(input.TakeWhile(char.IsDigit)));
}

Try it Online!

【讨论】:

    【解决方案2】:

    如果您想避免使用 Linq(但 TakeWhile 很不错),您可以重写代码以使用简单的 for 循环和 StringBuilder

    using System;
    using System.Text;
    
    public static void Main()
    {
        var input = "93434234adfjasdf asdfjksdfkl afjasdlfjl asdfjsdlkfjasldf ksdafjlaskdfjasdf";
        var sb = new StringBuilder();
        for (var counter = 0; char.IsDigit(input[counter]) && counter < input.Length; counter++) {
            sb.Append(input[counter]);
        }
    
        Console.WriteLine(sb.ToString());
    }
    

    Try it Online!

    【讨论】:

      【解决方案3】:
      (?<numbers>^[0-9]*)
      

      将从字符串开头开始匹配从 0 到 9 的所有数字,并将它们放入 &lt;numbers&gt; 组中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-09
        • 2011-01-10
        • 2011-12-04
        • 1970-01-01
        • 2020-12-11
        相关资源
        最近更新 更多