Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment a string with both letters and numbers

Tags:

c#

.net

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 would i increment this to "MD00496" & "MD00497" ect

If it was a normal string with numbers i would parse it to an int.

I have tried the following

 int i = int.Parse(sdesptchNo);
 i++;
 txtDispatchNo.Text = i.ToString();

Anyone any ideas how i would go about this.

like image 418
Inkey Avatar asked Mar 07 '13 10:03

Inkey


People also ask

Can I increment string in C++?

Increment the int 'Number' as your wish, then convert it into string and finally append it with the file name (or exactly where you want). This operation can be shorten into a single line: int Number = 123; string String = static_cast<ostringstream*>( &(ostringstream() << Number) )->str();


3 Answers

You first should figure out any commonality between the strings. If there is always a prefix of letters followed by digits (with a fixed width) at the end, then you can just remove the letters, parse the rest, increment, and stick them together again.

E.g. in your case you could use something like the following:

var prefix = Regex.Match(sdesptchNo, "^\\D+").Value;
var number = Regex.Replace(sdesptchNo, "^\\D+", "");
var i = int.Parse(number) + 1;
var newString = prefix + i.ToString(new string('0', number.Length));

Another option that might be a little more robust might be

var newString = Regex.Replace(x, "\\d+",
    m => (int.Parse(m.Value) + 1).ToString(new string('0', m.Value.Length)));

This would replace any number in the string by the incremented number in the same width – but leaves every non-number exactly the same and in the same place.

like image 124
Joey Avatar answered Oct 29 '22 09:10

Joey


Here is one Non-Regex way :P

string str = "MD00494";
string digits = new string(str.Where(char.IsDigit).ToArray());
string letters = new string(str.Where(char.IsLetter).ToArray());

int number;
if (!int.TryParse(digits, out number)) //int.Parse would do the job since only digits are selected
{
    Console.WriteLine("Something weired happened");
}

string newStr = letters + (++number).ToString("D5");

output would be:

newStr = "MD00495"
like image 25
Habib Avatar answered Oct 29 '22 10:10

Habib


Assuming that you only need to increment the numeric portion of the string, and that the structure of the strings is always - bunch of non-numeric characters followed by a bunch of numerals, you can use a regular expression to break up the string into these two components, convert the numeric portion to an integer, increment and then concatenate back.

var match = Regex.Match("MD123", @"^([^0-9]+)([0-9]+)$");
var num = int.Parse(match.Groups[2].Value);

var after = match.Groups[1].Value + (num + 1);
like image 38
Oded Avatar answered Oct 29 '22 08:10

Oded