Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert/remove hyphen to/from a plain string in c#?

I have a string like this;

   string text =  "6A7FEBFCCC51268FBFF";

And I have one method for which I want to insert the logic for appending the hyphen after 4 characters to 'text' variable. So, the output should be like this;

6A7F-EBFC-CC51-268F-BFF

Appending hyphen to above 'text' variable logic should be inside this method;

public void GetResultsWithHyphen
{
     // append hyphen after 4 characters logic goes here
}

And I want also remove the hyphen from a given string such as 6A7F-EBFC-CC51-268F-BFF. So, removing hyphen from a string logic should be inside this method;

public void GetResultsWithOutHyphen
{
     // Removing hyphen after 4 characters logic goes here
}

How can I do this in C# (for desktop app)? What is the best way to do this? Appreciate everyone's answer in advance.

like image 917
Idrees Khan Avatar asked Jul 11 '12 16:07

Idrees Khan


2 Answers

GetResultsWithOutHyphen is easy (and should return a string instead of void

public string GetResultsWithOutHyphen(string input)
{
    // Removing hyphen after 4 characters logic goes here
    return input.Replace("-", "");
}

for GetResultsWithHyphen, there may be slicker ways to do it, but here's one way:

public string GetResultsWithHyphen(string input)
{

    // append hyphen after 4 characters logic goes here
    string output = "";
    int start = 0;
    while (start < input.Length)
    {
        output += input.Substring(start, Math.Min(4,input.Length - start)) + "-";
        start += 4;
    }
    // remove the trailing dash
    return output.Trim('-');
}
like image 63
D Stanley Avatar answered Oct 26 '22 22:10

D Stanley


Use regex:

public String GetResultsWithHyphen(String inputString)
{
     return Regex.Replace(inputString, @"(\w{4})(\w{4})(\w{4})(\w{4})(\w{3})",
                                       @"$1-$2-$3-$4-$5");
}

and for removal:

public String GetResultsWithOutHyphen(String inputString)
{
    return inputString.Replace("-", "");
}
like image 29
Ria Avatar answered Oct 26 '22 22:10

Ria