Mikael
Mikael

Reputation: 982

Adding a character from the end of a string

I have a variety of strings in the following format:

WWSS1234519

S12319

etc.

All that I need to do is add a hyphen so that the 19 is separate. The above strings would become

This is C# in ASP.net, it's populating a gridview. Generic method with no insertions is:

 <asp:Label ID="AccLabel" runat="server" Text='<%# Eval("Acc") %>' Width="96px"/>

WWSS12345-19

S123-19

etc.

What I tried was finding the indexof the string based on "19" but that will change come new years and I don't want to have to update the code every year to get the hyphen to appear.

I know there's a simple way to do this - Just not sure how.

Thank you.

Upvotes: 2

Views: 2380

Answers (2)

mdelapena
mdelapena

Reputation: 185

If this will always be for the last 2 digits, use Insert(), for example:

str = str.Insert(str.Length - 2, "-");

Upvotes: 3

nikstffrs
nikstffrs

Reputation: 344

If the year is always just the last two characters just do an insert:

var s = "WWSS1234519";
var formatted = s.Insert(s.Length - 2, "-");

Upvotes: 7

Related Questions