Adding index to string

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,
I need to add an index to "GC-TI-0001" so that i can form the following
strings "GC-TI-0002", "GC-TI-0003", "GC-TI-0004", etc. Is there a fast and
easy way to do this in .NET or do i need to parse and then add and then add
the zeros?
 
Ibrahim said:
Hi,
I need to add an index to "GC-TI-0001" so that i can form the following
strings "GC-TI-0002", "GC-TI-0003", "GC-TI-0004", etc. Is there a fast and
easy way to do this in .NET or do i need to parse and then add and then add
the zeros?

Parse, add and format is what you have to do.

int num;
if (str.Length == 10 && int.TryParse(str.Substring(6), out num)) {
str = str.Substring(0, 6) + (++num).ToString("0000");
} else {
// wrong string format
}
 
Thanks for your reply!!!

Eversince i did this post, i came up with this, which is worked so far:

' to summarize
numberRepOfString = 5
newIndex = numberRepOfString + index
newString = String.Format("0005", newIndex)

but i don't know how it will do when the number is 0099 and then is
incremented by 1.
 
Ibrahim said:
Thanks for your reply!!!

Eversince i did this post, i came up with this, which is worked so far:

' to summarize
numberRepOfString = 5
newIndex = numberRepOfString + index
newString = String.Format("0005", newIndex)

but i don't know how it will do when the number is 0099 and then is
incremented by 1.

Hm... What is that code supposed to do, really? What does "Rep" in
"numberRepOfString" stand for? Repeat? Represent? Report? Where does the
number five come from, and what does the index variable contain?

If you want to format the number as three digits followed by a "5", it's
more clear to use a format containing it as a literal string: "000'5'".
 
I like the PadLeft & PadRight methods on the string class. You can provide
a total width and what the padding character is (like '0'). It will then
pad the string with padding characters until it reaches the specified
length.
 
Back
Top