简体   繁体   English

最简单的方法是将实际字符串值增加一

[英]Easiest way to Increase by one the actual string value

I have a string that i need to match with another array of string. 我有一个字符串,我需要与另一个字符串数组匹配。 If I found matches with the both array values then I have to split the numerical value from the string, and add 1 with that numerical value and append with the actual string with the new value. 如果我找到了两个数组值的匹配,那么我必须从字符串中拆分数值,并使用该数值加1 ,并使用新值附加实际字符串。 I tried in some splitting and concatenation. 我尝试了一些分裂和连接。 But I didn't get the proper and efficient way to solve the problem. 但我没有得到正确有效的方法来解决问题。 Below is my scenario. 以下是我的情景。

Actual Strings: 实际字符串:

BK-TS00023,X1-TS00000101,X4-A10000024,Y1-3,

Comparision String 比较字符串

BK Books      // Compare first two characters => BK Books matches with BK-TS00023
X1 Serials    // Compare first two characters => X1 Serials matches with X1-TS00000101

So, When I found the match with those strings, I need to get the numerical values like 00023 , 00000101 and increase the value by 1. Then append with default string. 所以,当我发现与之相匹配的这些字符串,我需要得到的数值像00023,00000101和增加1的值,然后用默认的字符串追加。 The resultant string will be something like this. 结果字符串将是这样的。

Result String 结果字符串

'BK-TS00024',
'X1-TS00000102',
'X4-A10000025',
'Y1-4'

I tried the below way. 我尝试了以下方式。 Please anyone help me to provide the proper way to do this scenario. 请任何人帮我提供正确的方法来完成这个场景。

Code

InfoType="BK Books"; // or "X1 Serials" // or etc ..
var splitInfo = InfoType.Split(' ');
        var SiteFileInfo = Db.SiteFiles.Where(asd => asd.Code == "AutoBarcode").Select(asd => asd.Line1).FirstOrDefault();
        var splitSiteFile = SiteFileInfo.Split(',');
        int cnt = 0;
        foreach (var s in splitSiteFile)
        {
            cnt += 1;
            if (s.Contains(splitInfo[0]))
            {

                //var infoSiteSplit = s.Split('-');
                var olyNumber = Regex.Split(s, @"(?<=\p{L})(?=\p{N})");
                int i = 0;
                string Truncstring = "";
                foreach (var a in olyNumber)
                {
                    bool result = int.TryParse(a, out i);
                    if (result)
                    {
                        i += 1;
                        int befconv = Convert.ToInt32(a);
                        Truncstring = s.Replace(befconv.ToString(), i.ToString());
                    }
                }
                splitSiteFile[cnt - 1] = Truncstring;
                string JoinString = string.Join(",", splitSiteFile);
                Db.ExecuteStoreCommand("update SiteFile set Line1={0} where Code={1}", JoinString, "AutoBarcode");
                Db.SaveChanges();
                return Truncstring;
            }
        }

You may use the Regex.Replace Method (String, String, MatchEvaluator) (and optionally, delegates instead of MatchEvaluator instances). 您可以使用Regex.Replace Method (String, String, MatchEvaluator) (以及可选的MatchEvaluator而不是MatchEvaluator实例)。

Try this (it will increase with 1 all matches in the filter): 试试这个(它将在过滤器中增加1个所有匹配项):

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

class Program
{
    static void Main(string[] args)
    {
        var input = "BK-TS00023,X1-TS00000101,X4-A10000024,Y1-3,";
        var filter = new[] { "BK Books", "X1 Serials" };
        Console.WriteLine(input);
        var result = IncreaseWithFilter(input, filter);
        Console.WriteLine(result);
    }

    private static string IncreaseWithFilter(
        string input,
        IEnumerable<string> filter)
    {
        var truncatedFilter = filter.Select(f => f.Substring(0, 2));
        var result = Regex.Replace(input, @"([^,].*?)\d+(?=,)",
            (match1) =>
            {
                var value = match1.Value;
                if (truncatedFilter.Any(f => match1.Value.StartsWith(f)))
                {
                    value = Regex.Replace(match1.Value, @"(?<=)\d+",
                        (match2) =>
                        {
                            return (Convert.ToInt32(match2.Value) + 1)
                                .ToString()
                                .PadLeft(match2.Value.Length, '0');
                        });
                }
                return value;
            });
        return result;
    }
}

Output: 输出:

BK-TS00023,X1-TS00000101,X4-A10000024,Y1-3,
BK-TS00024,X1-TS00000102,X4-A10000024,Y1-3,

Sample usage in your code: 代码中的示例用法:

InfoType = "BK Books";
var SiteFileInfo = Db.SiteFiles
    .Where(asd => asd.Code == "AutoBarcode")
    .Select(asd => asd.Line1)
    .FirstOrDefault();
var result = IncreaseWithFilter(
    SiteFileInfo, 
    new[] { InfoType });

Why don't you simply take the right part (the number part) of the string, convert it to int, increase it and convert to string again? 为什么不简单地使用字符串的正确部分(数字部分),将其转换为int,增加它并再次转换为字符串?

Something like: 就像是:

public string IncreaseByOne(string original) {
  var numberpart = "";
  var index = original.Length - 1;
  while (index != 0) {
    var oneletter = original.Substring(index, 1);
    var isint = int.TryParse(oneletter, out digit);
    if (!isint) break;
    numberpart += oneletter;
    --index;
  }
  var firstpart = original.Substring(0, orignal.Length - numberpart.Length);
  var padlength = numberpart.Length;
  int value;
  int.TryParse(numberpart, out value);
  var result = ++value.ToString().PadLeft(padlength, '0');
  return firstpart + result;
}

Just as an extra tip that could simplify the string creation after increasing the int, instead of calculating the length of the string and do PadLeft with zero's, you can also take an int and use StringFormat IFormatProvider to add the leading zero's: 正如在增加int之后可以简化字符串创建的额外提示,而不是计算字符串的长度并使用零的PadLeft,您还可以使用int并使用StringFormat IFormatProvider来添加前导零:

string paddedString = String.Format("TS{1:00000}", count); 
//when count = 24, should output "TS00024"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM