Author Topic: Increment a Number in a String  (Read 8808 times)

0 Members and 1 Guest are viewing this topic.

SteveK

  • Guest
Increment a Number in a String
« on: July 29, 2010, 04:46:53 AM »
Hi,

I have a string. I need a function that finds the last number in the string and increments it by an integer (parameter) then returns the string again.
I'm sure you can do this with regular expressions but I don't know how.

Example 1: (negative increment)
input string = a3
value to increment = -1
string returned = a2

Example 2: (multiple numbers in the string)
input string = ab12cd34e
value to increment = 2
string returned = ab12cd36e

Example 3: (ignoring decimal places)
input string a1.9b
value to increment = 1
string returned = a1.10b

Programming in C#. Any help is appreciated.

pkohut

  • Guest
Re: Increment a Number in a String
« Reply #1 on: July 29, 2010, 05:01:39 AM »
Example 2: (multiple numbers in the string)
input string = ab12cd34e
value to increment = 2
string returned = ab12cd36e

Example 3: (ignoring decimal places)
input string a1.9b
value to increment = 1
string returned = a1.10b

Are the numbers limited to a range and subject to rollover, like an odometer? Can't tell from examples 1 and 2. Example 3 suggests not. Let's clarify using a modified example 2.

Code: [Select]
input string ab12cd98e
value to increment = 2
string returned = ab12cd00e or ab12cd100e ??

Similar question for negative increments. And with negative increments, is 0 a floor or are negative results acceptable?

Andrey Bushman

  • Swamp Rat
  • Posts: 864
Re: Increment a Number in a String
« Reply #2 on: July 29, 2010, 06:00:52 AM »
Code: [Select]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Incr("asdf123", 5));
            Console.WriteLine(Incr("asdf555_red123", -7));
            Console.Read();
        }

        static string Incr(string text, int increment)
        {
            int i = Int32.Parse(new string(text.Reverse().TakeWhile(n => Char.IsNumber(n)).Reverse().ToArray()));
            string name = text.Substring(0, text.Length - i.ToString().Length);
            return name + (i + increment);
        }
    }
}

SteveK

  • Guest
Re: Increment a Number in a String
« Reply #3 on: July 29, 2010, 06:04:41 AM »
Are the numbers limited to a range and subject to rollover, like an odometer? Can't tell from examples 1 and 2. Example 3 suggests not. Let's clarify using a modified example 2.

Code: [Select]
input string ab12cd98e
value to increment = 2
string returned = ab12cd00e or ab12cd100e ??

Similar question for negative increments. And with negative increments, is 0 a floor or are negative results acceptable?
pkohut, I should have added, range is not limited in positive direction, and assume 0 is floor.

Andrey, I will try your code and let you know.


SteveK

  • Guest
Re: Increment a Number in a String
« Reply #4 on: July 29, 2010, 06:16:00 AM »
Code: [Select]
        static string Incr(string text, int increment)
        {
            int i = Int32.Parse(new string(text.Reverse().TakeWhile(n => Char.IsNumber(n)).Reverse().ToArray()));
            string name = text.Substring(0, text.Length - i.ToString().Length);
            return name + (i + increment);
        }
Thanks for the code Andrey. It takes me further along than I was, however I get an error when letters are at the end of my string. The last number can be anywhere in the string, even at the start.

fixo

  • Guest
Re: Increment a Number in a String
« Reply #5 on: July 29, 2010, 07:11:48 AM »
Hi,

I have a string. I need a function that finds the last number in the string and increments it by an integer (parameter) then returns the string again.
I'm sure you can do this with regular expressions but I don't know how.

Example 1: (negative increment)
input string = a3
value to increment = -1
string returned = a2

Example 2: (multiple numbers in the string)
input string = ab12cd34e
value to increment = 2
string returned = ab12cd36e

Example 3: (ignoring decimal places)
input string a1.9b
value to increment = 1
string returned = a1.10b

Programming in C#. Any help is appreciated.

Hi Steve
Send me test message on my home address
coz I've lost your e-mail
I have complete project (not finished yet,
but it may helps)
I've used RegularExpression to rebuild sttring

~'J'~

SteveK

  • Guest
Re: Increment a Number in a String
« Reply #6 on: July 29, 2010, 07:29:09 AM »
Hi Oleg,

You have a complete project? But I'm just after one function!  :-)

steve

Andrey Bushman

  • Swamp Rat
  • Posts: 864
Re: Increment a Number in a String
« Reply #7 on: July 29, 2010, 07:33:25 AM »
The last number can be anywhere in the string, even at the start.
Code: [Select]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Incr("asdf123", 5));
            Console.WriteLine(Incr("asdf555_red123", -7));
            Console.WriteLine(Incr("asdf555_red123dwq", -2));
            Console.WriteLine(Incr("543asdf", -7));
            Console.WriteLine(Incr("asdf555_red123dwq1", -5));
            Console.WriteLine(Incr("rrasdf", 8));
            Console.Read();
        }

        static string Incr(string text, int increment)
        {
            if (text.Where(n => Char.IsNumber(n)).Count() == 0)
            {
                Console.WriteLine("string '{0}' not contain of number", text);
                return string.Empty;
            }
            string revText = new string(text.Reverse().ToArray());
            string a = new string(revText.TakeWhile(n => !Char.IsNumber(n)).ToArray());
            int b = Int32.Parse(new string(revText.Skip(a.Length).TakeWhile(n => Char.IsNumber(n)).Reverse().ToArray())) + increment;
            string c = revText.Substring(a.Length + b.ToString().Length);
            StringBuilder sb = new StringBuilder();
            sb.Append(a);
            sb.Append(new string(b.ToString().Reverse().ToArray()));
            sb.Append(c);            
            return new string(sb.ToString().Reverse().ToArray());
        }
    }
}
« Last Edit: July 29, 2010, 07:39:58 AM by Hwd »

SteveK

  • Guest
Re: Increment a Number in a String
« Reply #8 on: July 29, 2010, 07:41:55 AM »
Thank you Hwd, I can deffinately use this.

Cheers! :-)

Andrey Bushman

  • Swamp Rat
  • Posts: 864
Re: Increment a Number in a String
« Reply #9 on: July 29, 2010, 08:27:51 AM »
Thank you Hwd, I can deffinately use this.

Cheers! :-)

I will forgive pardons - I have skipped an error for it variant string:
"asdf555_red123dwq00001":

I has rectified an error:

Code: [Select]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Incr("asdf123", 5));
            Console.WriteLine(Incr("asdf555_red123", -7));
            Console.WriteLine(Incr("asdf555_red123dwq", -2));
            Console.WriteLine(Incr("543asdf", -7));
            Console.WriteLine(Incr("asdf555_red123dwq1", -5));
            Console.WriteLine(Incr("asdf555_red123dwq00001", -5));//It test add
            Console.WriteLine(Incr("rrasdf", 8));
            Console.Read();
        }

        static string Incr(string text, int increment)
        {
            if (text.Where(n => Char.IsNumber(n)).Count() == 0)
            {
                Console.WriteLine("string '{0}' not contants of nomber", text);
                return string.Empty;
            }
            string revText = new string(text.Reverse().ToArray());
            string a = new string(revText.TakeWhile(n => !Char.IsNumber(n)).ToArray());
            string z = new string(revText.Skip(a.Length).TakeWhile(n => Char.IsNumber(n)).Reverse().ToArray());
            int b = Int32.Parse(z) + increment;
            if (b > 0)
            {
                z = z.Length == b.ToString().Length ? b.ToString() : new string('0', z.Length - b.ToString().Length) + b;
            }
            else
            {
                z = z.Length == b.ToString().Length ? b.ToString() : new string('0', z.Length + 1 - b.ToString().Replace("-","").Length) + Math.Abs(b);
            }
           
            string c = revText.Substring(a.Length + z.Length);
            StringBuilder sb = new StringBuilder();
            sb.Append(a);
            sb.Append(new string(z.Reverse().ToArray()));
            sb.Append(c);           
            return new string(sb.ToString().Reverse().ToArray());
        }
    }
}
« Last Edit: July 29, 2010, 08:51:12 AM by Hwd »

SteveK

  • Guest
Re: Increment a Number in a String
« Reply #10 on: July 29, 2010, 09:13:30 AM »
Thanks for your help so far Hwd.

I did find another error though. Try for example:
Code: [Select]
Console.WriteLine(Incr("9a", 1));
Console.WriteLine(Incr("a99b", 1));

Edit: Also, a problem with having Replace("-","") in the code is that sometimes there are hyphen's in the string and it'd remove them.
« Last Edit: July 29, 2010, 09:28:59 AM by steve.k »

Andrey Bushman

  • Swamp Rat
  • Posts: 864
Re: Increment a Number in a String
« Reply #11 on: July 29, 2010, 09:58:48 AM »
Thanks for your help so far Hwd.

I did find another error though. Try for example:
Code: [Select]
Console.WriteLine(Incr("9a", 1));
Console.WriteLine(Incr("a99b", 1));

Edit: Also, a problem with having Replace("-","") in the code is that sometimes there are hyphen's in the string and it'd remove them.
Test it please:
Code: [Select]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Incr("asdf123", 5));
            Console.WriteLine(Incr("asdf555_red123", -7));
            Console.WriteLine(Incr("asdf555_red123dwq", -2));
            Console.WriteLine(Incr("543asdf", -7));
            Console.WriteLine(Incr("asdf555_red123dwq1", -5));
            Console.WriteLine(Incr("asdf555_red123dwq00001", -5));
            Console.WriteLine(Incr("9a", 1));
            Console.WriteLine(Incr("a99b", 1));
            Console.WriteLine(Incr("999", -11));
            Console.WriteLine(Incr("rrasdf", 8));
           
            Console.Read();
        }

        static string Incr(string text, int increment)
        {
            if (text.Where(n => Char.IsNumber(n)).Count() == 0)
            {
                Console.WriteLine("string '{0}' not contants of nomber", text);
                return string.Empty;
            }
            string revText = new string(text.Reverse().ToArray());
            string a = new string(revText.TakeWhile(n => !Char.IsNumber(n)).ToArray());
            string z = new string(revText.Skip(a.Length).TakeWhile(n => Char.IsNumber(n)).Reverse().ToArray());
            string d = z;
            int zc = z.Length - Int32.Parse(z).ToString().Length;// count of 0.
            int b = Int32.Parse(z) + increment;
            if (b > 0)
            {
                z = z.Length == b.ToString().Length ? b.ToString() : new string('0', zc) + b;
            }
            else
            {
                z = z.Length == b.ToString().Length ? b.ToString() : new string('0', zc + 1) + Math.Abs(b);
            }
           
            string c = revText.Substring(a.Length + d.Length);
            StringBuilder sb = new StringBuilder();
            sb.Append(a);
            sb.Append(new string(z.Reverse().ToArray()));
            sb.Append(c);           
            return new string(sb.ToString().Reverse().ToArray());
        }
    }
}

SteveK

  • Guest
Re: Increment a Number in a String
« Reply #12 on: July 29, 2010, 10:23:53 AM »
That's better, no errors, thanks:

I was also messing around with it as I've learnt from your code and I came up with:
Code: [Select]
static string Incr(string text, int increment)
{
    if (text.Where(n => Char.IsNumber(n)).Count() == 0)
        return null;
    string revText = new string(text.Reverse().ToArray());
    string a = new string(revText.TakeWhile(n => !Char.IsNumber(n)).ToArray());
    string z = new string(revText.Skip(a.Length).TakeWhile(n => Char.IsNumber(n)).Reverse().ToArray());
    string y = new string(z.TakeWhile(n => n.Equals('0')).ToArray());
    string c = revText.Substring(a.Length + z.Length);
    int b = Int32.Parse(z) + increment;
    if (b < 0) b = 0;
    z = b.ToString();
    StringBuilder sb = new StringBuilder();
    sb.Append(a);
    sb.Append(new string(z.Reverse().ToArray()));
    sb.Append(y);
    sb.Append(c);
    return new string(sb.ToString().Reverse().ToArray());
}
Very similar to yours. Again, thanks for your help Hwd.  :-)

Andrey Bushman

  • Swamp Rat
  • Posts: 864
Re: Increment a Number in a String
« Reply #13 on: July 29, 2010, 10:31:43 AM »
Again, thanks for your help Hwd.  :-)
:-)

fixo

  • Guest
Re: Increment a Number in a String
« Reply #14 on: July 29, 2010, 11:34:31 AM »
That's better, no errors, thanks:

I was also messing around with it as I've learnt from your code and I came up with:
Code: [Select]
static string Incr(string text, int increment)
{
    if (text.Where(n => Char.IsNumber(n)).Count() == 0)
        return null;
    string revText = new string(text.Reverse().ToArray());
    string a = new string(revText.TakeWhile(n => !Char.IsNumber(n)).ToArray());
    string z = new string(revText.Skip(a.Length).TakeWhile(n => Char.IsNumber(n)).Reverse().ToArray());
    string y = new string(z.TakeWhile(n => n.Equals('0')).ToArray());
    string c = revText.Substring(a.Length + z.Length);
    int b = Int32.Parse(z) + increment;
    if (b < 0) b = 0;
    z = b.ToString();
    StringBuilder sb = new StringBuilder();
    sb.Append(a);
    sb.Append(new string(z.Reverse().ToArray()));
    sb.Append(y);
    sb.Append(c);
    return new string(sb.ToString().Reverse().ToArray());
}
Very similar to yours. Again, thanks for your help Hwd.  :-)

Hope you don't mind but how about:

Code: [Select]
Console.WriteLine(Incr("asdf0004", -5));
~'J'~

SteveK

  • Guest
Re: Increment a Number in a String
« Reply #15 on: July 29, 2010, 11:52:03 AM »
how about:
Code: [Select]
Console.WriteLine(Incr("asdf0004", -5));~'J'~
At the moment I'm not sure what is better for my purposes, to go into the negatives or to floor at 0, but since I said "stop at 0" near the start of the thread I've stayed with that. In time it might change.

Glenn R

  • Guest
Re: Increment a Number in a String
« Reply #16 on: July 30, 2010, 05:53:18 AM »
A quickie with regular expressions:
Code: [Select]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Text.RegularExpressions;

namespace IncStr
{
    class Program
    {
        static void Main(string[] args)
        {
            //string test1 = "ab12cd-34e";
            string test2 = "a1.9b";
            //string test3 = "ab12cd34e66";

            string pattern = "[-+]?[0-9]+";

            MatchCollection matches = Regex.Matches(test2, pattern);

            if (matches == null || matches.Count == 0) return;

            foreach (Match match in matches)
            {
                Console.WriteLine("{0}Match index: {1}", Environment.NewLine, match.Index);
                Console.WriteLine("{0}Match value: {1}", Environment.NewLine, match.Value);
                Console.WriteLine("{0}Match length: {1}", Environment.NewLine, match.Length);
            }

            // work with the last match only...
            Match lastMatch = matches[matches.Count - 1];

            int testIncrement = 2;

            int newValue;
            bool result = int.TryParse(lastMatch.Value, out newValue);

            string replacedString = test2.Substring(0, lastMatch.Index) +
                                    (newValue + testIncrement) +
                                    test2.Substring(lastMatch.Index + lastMatch.Length);

            Console.WriteLine(replacedString);

            Console.ReadLine();
        }
    }
}

SteveK

  • Guest
Re: Increment a Number in a String
« Reply #17 on: July 30, 2010, 07:31:52 AM »
Thanks Glenn.  :-)
It doesn't keep zero prefixes, but I'm happy to see a regex example anyway.

Glenn R

  • Guest
Re: Increment a Number in a String
« Reply #18 on: July 30, 2010, 07:37:11 AM »
It's just an example to show what's possible. It's up to you or somebody else to come up with the arcane regex incantation needed :D

SteveK

  • Guest
Re: Increment a Number in a String
« Reply #19 on: July 30, 2010, 10:34:34 AM »
the arcane regex incantation needed :D
That's exactly what I thought when I was trying to work it out - by the time I learn the required regex combination I could have twice written something from scratch that does it. Probably worthwhile to know, but it's a language inside a language.

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: Increment a Number in a String
« Reply #20 on: July 31, 2010, 04:35:48 AM »
noticed this a couple of weeks ago
Regex Editor Add-on
http://visualstudiogallery.msdn.microsoft.com/en-us/55c24bf1-2636-4f94-831d-28db8505ce00?SRC=VSIDE

Haven't made time to look at it yet.
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.