Adding index to string

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?
 
G

Guest

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
}
 
G

Guest

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.
 
G

Guest

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'".
 
A

Andrew Faust

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top