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

时间:2013-07-10 10:43:47

标签: c# string

我有一个字符串,我需要与另一个字符串数组匹配。如果我找到了两个数组值的匹配,那么我必须从字符串中拆分数值,并使用该数值添加 1 ,并使用新值追加实际字符串。我尝试了一些分裂和连接。但我没有得到正确有效的方法来解决问题。以下是我的情景。

实际字符串:

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

比较字符串

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

所以,当我找到与这些字符串的匹配时,我需要得到像 00023 00000101 这样的数值,然后将值增加1.然后附加默认值串。结果字符串将是这样的。

结果字符串

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

我尝试了以下方式。请任何人帮我提供这种方案的正确方法。

代码

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;
            }
        }

3 个答案:

答案 0 :(得分:1)

您可以使用Regex.Replace Method (String, String, MatchEvaluator)(以及可选的代理人而不是MatchEvaluator个实例)。

尝试此操作(过滤器中的所有匹配项将增加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;
    }
}

输出:

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

代码中的示例用法:

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

答案 1 :(得分:1)

为什么不简单地选择字符串的正确部分(数字部分),将其转换为int,增加它并再次转换为字符串?

类似的东西:

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;
}

答案 2 :(得分:1)

作为一个额外的提示,可以在增加int之后简化字符串创建,而不是计算字符串的长度并使用零的PadLeft,你也可以使用int并使用StringFormat IFormatProvider来添加前导零: / p>

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