Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment a number within a string (C#)

Tags:

string

c#

I have a string with a number at the end, after a dash ("-"). I'd like to create that same string with that number incremented by 1. Pretty simple, but I'm wondering if there's a better approach to this? Thanks!

string oldString = "BA-0001-3";
int lastIndex = oldString.LastIndexOf("-");
string oldNumber = oldString.SubString(lastIndex + 1);
string oldPartialString = oldString.SubString(0, lastIndex);
int newNumber = Convert.ToInt32(oldNumber) + 1;

string newString = oldPartialString + newNumber.ToString();
like image 559
morganpdx Avatar asked Nov 23 '25 09:11

morganpdx


1 Answers

Regex?

Example:

Regex.Replace("BA-0001-3", @"[A-Z]{2}-\d{4}-(\d+)", 
    m => (Convert.ToInt32(m.Groups[1].Value) + 1).ToString())
like image 116
gandjustas Avatar answered Nov 24 '25 21:11

gandjustas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!