简体   繁体   中英

C#: Increment only the last number of a String

I have strings that look like this:

1.23.4.34

12.4.67

127.3.2.21.3

1.1.1.9

This is supposed to be a collection of numbers, separated by '.' symbols, similar to an ip address. I need to increment only the last digit/digits.

Expected Output:

1.23.4.35

12.4.68

127.3.2.21.4

1.1.1.10

Basically, increment whatever the number that is after the last '.' symbol.

I tried this:

char last = numberString[numberString.Length - 1];
int number = Convert.ToInt32(last);
number = number + 1;

If I go with the above code, I just need to replace the characters after the last '.' symbol with the new number. How do I get this done, good folks? :)

It seems to me that one method would be to:

  • split the string on . to get an array of components.
  • turn the final component into an integer.
  • increment that integer.
  • turn it back into a string.
  • recombine the components with . characters.

See, for example, the following program:

using System;

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            String original = "1.23.4.34";
            String[] components = original.Split('.');
            int value = Int32.Parse(components[components.Length - 1]) + 1;
            components[components.Length - 1] = value.ToString();
            String newstring = String.Join(".",components);
            Console.WriteLine(newstring);
        }
    }
}

which outputs the "next highest" value of:

1.23.4.35

You can use string.LastIndexOf().

string input = "127.3.2.21.4";
int lastIndex = input.LastIndexOf('.');
string lastNumber = input.Substring(lastIndex + 1);
string increment = (int.Parse(lastNumber) + 1).ToString();
string result = string.Concat(input.Substring(0, lastIndex + 1), increment);

You need to extract more than just the last character. What if the last character is a 9 and then you add 1 to it? Then you need to correctly add one to the preceding character as well. For example, the string 5.29 should be processed to become 5.30 and not simply 5.210 or 5.20.

So I suggest you split the string into its number sections. Parse the last section into an integer. Increment it and then create the string again. I leave it as an exercise for the poster to actually write the few lines of code. Good practice!

Something like this:

var ip = "1.23.4.34";
var last = int.Parse(ip.Split(".".ToCharArray(), 
                StringSplitOptions.RemoveEmptyEntries).Last());
last = last + 1;
ip = string.Format("{0}.{1}",ip.Remove(ip.LastIndexOf(".")) , last);

If you are dealing with IP, there will be some extra code in case of .034, which should be 035 instead of 35. But that logic is not that complicated.

It's simple as this, use Split() and Join() String methods

 String test = "1.23.4.34"; // test string

 String[] splits = test.Split('.'); // split by .

 splits[splits.Length - 1] = (int.Parse(splits[splits.Length - 1])+1).ToString(); // Increment last integer (Note : Assume all are integers)

 String answ = String.Join(".",splits); // Use string join to make the string from string array. uses . separator 

 Console.WriteLine(answ); // Answer  : 1.23.4.35

Using a bit of Linq

int[] int_arr = numberString.Split('.').Select(num => Convert.ToInt32(num)).ToArray();

int_arr[int_arr.Length - 1]++;
numberString = "";

for(int i = 0; i < int_arr.Length; i++) {
    if( i == int_arr.Length - 1) {
        numberString += int_arr[i].ToString();
    }
    else {
        numberString += (int_arr[i].ToString() + ".");
    }

}

Note: on phone so can't test.

My Solution is:

private static string calcNextCode(string value, int index)
{
    if (value is null) return "1";
    if (value.Length == index + 1) return value + "1";

    int lastNum;
    int myIndex = value.Length - ++index;
    char myValue = value[myIndex];

    if (int.TryParse(myValue.ToString(), NumberStyles.Integer, null, out lastNum))
    {
        var aStringBuilder = new StringBuilder(value);

        if (lastNum == 9)
        {
            lastNum = 0;
            aStringBuilder.Remove(myIndex, 1);
            aStringBuilder.Insert(myIndex, lastNum);
            return calcNextCode(aStringBuilder.ToString(), index++);
        }
        else
        {
            lastNum++;
        }
        aStringBuilder.Remove(myIndex, 1);
        aStringBuilder.Insert(myIndex, lastNum);
        return aStringBuilder.ToString();
    }

    return calcNextCode(value, index++);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM