【问题标题】:Best way to extract two numbers and following letter from string从字符串中提取两个数字和以下字母的最佳方法
【发布时间】:2012-12-19 19:09:52
【问题描述】:

假设我们有一个字符串,称为源。它包含“纽约市 - 12A - 1234B”

规则如下:

一个。我们知道应该保留最接近字符串开头的两个数字,连同后面的字符并放入一个单独的字符串中,称为结果;

b.我们不确定下面这个字符是数字还是字母

c。字符串本身的格式各不相同 - 可能是“NY 12A 1234B”

d。我们可以不关心其他任何事情!

现在我以我无限的智慧创造了这个怪物。它有效,但告诉我有更好的方法来做到这一点,或者充其量是一种更清洁、更注重性能的方法。

class Program
    {
        public static int i = 0;
        public static int q = 0;
        public static int x = 0;
        public static string source = "New York City - 12A - 1234B";
        public static string results = "";
        public static char[] from_source_char;
        public static List<string> from_source_list = new List<string>();

        static void Main(string[] args)
        {
            from_source_char = source.ToCharArray();
            foreach (char unit in from_source_char)
            {
                from_source_list.Add(unit.ToString());
            }


            Console.WriteLine("Doing while " + i.ToString() + " < " + (from_source_list.Count() - 1).ToString());
            while (i < from_source_list.Count() - 1)
            {
                Console.WriteLine("i is at " + i.ToString());
                Console.WriteLine("Examining " + from_source_list[i].ToString());

                try
                {
                    q = Convert.ToInt32(from_source_list[i]);
                    results += from_source_list[i].ToString();
                    Console.WriteLine("Found part 1!");
                    x++;
                }
                catch
                {
                    Console.WriteLine("Disregarding " + from_source_list[i].ToString());
                    // do nothing
                }

                if (x == 2)
                {
                    Console.WriteLine("Found final part! " + from_source_char[i+1].ToString());
                    results += from_source_char[i+1].ToString();
                    break;
                }

                i++;

            }

            Console.WriteLine("Result is " + results.ToString());
            Thread.Sleep(999999);
        }
    }

【问题讨论】:

  • 这个字符串有一个通用的格式??像 XXXX - 00X - 0000X 或者可以不同?
  • 不,在许多情况下格式化是随机的,但我们总是知道前两个数字是我们开始的地方。

标签: c# string integer


【解决方案1】:

您可以将Regex 与此模式一起使用:@"^.*?(?&lt;numbers&gt;\d{2}\w).*$"

例子:

var f = @"^.*?(?<numbers>\d{2}\w).*$";
var match = Regex.Match("NY 12A 1234B", f);
var result = match.Groups["numbers"].Value;

【讨论】:

  • 他投篮,他得分!看起来我需要检查正则表达式的文档。我会尽快回答。
【解决方案2】:

另一个没有正则表达式的版本:

char a = source.First(pos => char.IsDigit(pos));
int b = source.IndexOf(a);
string result = source.Substring(b, 3);
Console.WriteLine(result);

【讨论】:

    猜你喜欢
    • 2011-11-21
    • 2017-07-30
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    相关资源
    最近更新 更多