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