-4

I want to store some string code in SQL like 120.002.123 or EXP.120.555. How can I split those strings to increase only the rightmost integer part? I don't want to change other parts of the string.

Ex. 120.002.124 or EXP.120.556

How can I do this in C#?

M. Adeel Khalid
  • 1,786
  • 2
  • 21
  • 24
  • 5
    Why are you storing it as a string if you want to increment it? What code have you tried already? – Ben Feb 07 '17 at 07:41

2 Answers2

1

This might do the trick for you

string str = "EXP.120.556"; //120.002.123
str = String.Join(
                    ".", 
                    str.Split('.')
                        .Take(
                                str.Split('.').Length - 1
                             )
                 ) 
                 + "." + 
                 (
                    Convert.ToInt32
                    (
                        str.Split('.').LastOrDefault()
                    ) + 1
                 ).ToString();

So here in the code the first String.Join will join the other part of the string with . except of the last part which you want to increament using Take. Then Convert.ToInt32 will convert the last part of the string to a integer using LastOrDefault and then we add 1 to it and again convert it back to string using ToString

Mohit S
  • 13,723
  • 6
  • 34
  • 69
0

What you can do is to use String.Split method and split by . to get each individual number.

string test = "120.002.123";
string[] allparts = test.Split('.');

Then take the last entry and convert it to an integer

int lastNumber = Convert.ToInt32(allparts.Last());

Now you can do what ever you want with that integer.

With a little more research effort you could have solved it on your own. Like this + this

Community
  • 1
  • 1
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76