generate hyphen key

In this example i am trying to do some string manipulation.
Depending on the value of this string different sorts of new hyphenated string will be generated.

Such as
Input String is “data”, output will be “data-1”
Input String is “data-1”, output will be “data-2”
Input String is “data-1a”, output will be “data-1a-1” and so on.

If the suffix of the string is not numerical then new integer value will be appended.

You can better try experimenting this using the fiddle here.

using System;

public class Program
public static void Main()
string data = "gokul2-5a";
string hyphened_data = string.Empty;
string valueBeforeLastHyphen = string.Empty;
string valueAfterLastHyphen = string.Empty;
int indexOfHyphen = data.LastIndexOf("-");
// If Hypnen is found in ContractCode
if (indexOfHyphen != -1)
valueBeforeLastHyphen = data.Substring(0, indexOfHyphen).Trim();
valueAfterLastHyphen = data.Substring(indexOfHyphen + 1).Trim();
// increment valueAfterLastHyphen
int suffixNum;
if (int.TryParse(valueAfterLastHyphen, out suffixNum))
hyphened_data = String.Format("{0}-{1}", valueBeforeLastHyphen, suffixNum + 1);
hyphened_data = String.Format("{0}-1", data);
// Id contractCode has no hyphen
hyphened_data = String.Format("{0}-1", data);



About Gokul Dahal, Nepal

Software Engineer, Freelancer, Design and Develop web applications,Software Developer Nepal, FreeLancer Nepal Contact :
This entry was posted in C#. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s