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();
I would probably use my friend
string.Split:A small tweak that will perhaps make it quicker (by accessing
parts.Lengthand subtracting 1 only once – didn’t profile so it’s purely a guess, and it is likely a marginal difference anyway), but above all more robust (by usingint.TryParse):