【问题标题】:Search for a substring which ends in a varying integer搜索以可变整数结尾的子字符串
【发布时间】:2017-06-01 10:41:42
【问题描述】:

以这个场景为例。

我有一个有时可以以" - C(N)" 结尾的字符串,其中(N) 是一个变化的正数整数

你将如何验证字符串是否包含这种子字符串?我认为这是一个有趣的案例,我想看看人们如何以最整洁和最有效的方式解决它。 (我正在使用 C#

例如

"ABC - CA" 将返回 false

"ABC - C20" 将返回 true

【问题讨论】:

  • 您需要为此使用正则表达式
  • ABC2 会返回真还是假?
  • @Oscar 我认为这是最整洁、最有效的方式。
  • @MattJones false 如果 (N) 为 2,则它需要为“-C2”

标签: c# string


【解决方案1】:

我建议使用正则表达式

string source = "ABC - C20";

bool result = Regex.IsMatch(source, " - C[0-9]+$");    

【讨论】:

  • 这似乎是迄今为止更好的方法。但是如果子字符串在字符串的开头或中间而不是结尾呢?
  • @Jurgen Cuschieri:这就是为什么我把 $ anchor 放在了比赛的 end
【解决方案2】:

你可以试试这样的:

int result = 0;
var success = Int32.TryParse(yourString.Substring(yourString.LastIndexOf(" - C") + 4), out result);

if(result <= 0){
    success = false;
}

【讨论】:

  • 反例:"ABC - C-3" 因为-3 是一个有效整数;另一个反例(一个 eerie 之一)"ABC - C9876543210"9876543210 是一个有效整数时,它高于int32.MaxValue
  • @Dmitry Bychenko - 因为 -3 是一个有效的整数,所以一切都应该没问题。
  • 就我而言,我忘了补充说它只能是一个正整数。我的错...编辑的问题。
  • 请将.IndexOf 也更改为.LastIndexOf:否则"ABC - C123 bla-bla-bla" 将成为反例。
  • 完成。好电话=)
【解决方案3】:

使用正则表达式

using System.Collections.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication57
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] inputs = {
                                "ABC - CA",
                                "ABC - C20"
                            };

            string pattern = @"\w+\s+-\s+\w+\d+$";

            foreach (string input in inputs)
            {
                Console.WriteLine("Input : '{0}' Matches : '{1}'", input, Regex.IsMatch(input,pattern) == true ? "True" : "False");
            }

            Console.ReadLine();
        }

    }


}

【讨论】:

    【解决方案4】:

    在 excel (VBA) 中,您可以找到最后一个字符是否为 alpha。

    =ISALPHA(RIGHT(String, 1) 将为 ABC - CA 提供 true,为 ABC - C20 提供 false

    您可以使用适当的语法使用 C# 调整解决方案

    【讨论】:

    • 不,.Net 中没有这样的 ISALPHA 功能
    猜你喜欢
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 2018-08-24
    • 2023-03-19
    相关资源
    最近更新 更多