Increment a string with both letters and numbers

前端 未结 8 1826
故里飘歌
故里飘歌 2020-12-19 00:50

I have a string which i need to increment by 1 The string has both characters and numeric values.

The string layout i have is as follows \"MD00494\"

How woul

8条回答
  •  攒了一身酷
    2020-12-19 01:12

    I use this to Increment/Decrement Barcodes

    /// 
    /// Gets the number portion of the string and adds 1 to it
    /// 
    public static string IncrementNumbers(this string numString)
    {
      if (numString.IsEmpty())
        return numString;
      else if (!numString.Where(Char.IsDigit).Any())
        return numString;
      else
      {
        string prefix = Regex.Match(numString, "^\\D+").Value;
        string number = Regex.Replace(numString, "^\\D+", "");
        int i = int.Parse(number) + 1;
        return prefix + i.ToString($"D{numString.Length - prefix.Length}");
      }
    }
    
    /// 
    /// Gets the number portion of the string and subtracts 1 from it
    /// 
    public static string DecrementNumbers(this string numString)
    {
      if (numString.IsEmpty())
        return numString;
      else if (!numString.Where(Char.IsDigit).Any())
        return numString;
      else
      {
        string prefix = Regex.Match(numString, "^\\D+").Value;
        string number = Regex.Replace(numString, "^\\D+", "");
        int i = int.Parse(number) - 1;
        return prefix + i.ToString($"D{numString.Length - prefix.Length}");
      }
    }
    
    /// 
    /// Shortented IsNullOrWhiteSpace 
    /// 
    public static bool IsEmpty(this string str)
    {
      if (str.TrimFix() == null)
        return true;
    
      return false;
    }
    
    /// 
    /// Trims the String and returns Null if it's empty space
    /// 
    public static string TrimFix(this string rawString)
    {
      if (!string.IsNullOrWhiteSpace(rawString))
      {
        return rawString.Trim();
      }
      return null;
    }
    

提交回复
热议问题