Increment Number At End Of String - CSharp System

CSharp examples for System:String Number

Description

Increment Number At End Of String

Demo Code


using System.Text;
using System.Linq;
using System;/*from   www  .j  av a2s  .  c  om*/

public class Main{
        public static string IncrementNumberAtEndOfString(this string src)
        {
            // has this already been inc'd?
            var lastChars = src.SplitDot().LastOrDefault();
            if (lastChars==null)
            {
                return src + ".01";
            }
            else
            {
                int lastNum;
                bool isNum = int.TryParse(lastChars, out lastNum);
                if (!isNum) return src + ".01";
                return src.Substring(0, src.Length - lastChars.Length) + (++lastNum);
            }
        }
        public static string[] SplitDot(this string src)
        {
            return src.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
        }
}

Related Tutorials