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



Solution 1:[1]

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("-", "");
}

Solution 2:[2]

Here's the shortest regex I could come up with. It will work on strings of any length. Note that the \B token will prevent it from matching at the end of a string, so you don't have to trim off an extra hyphen as with some answers above.

    using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "6A7FEBFCCC51268FBFF";
            for (int i = 0; i <= text.Length;i++ )
                Console.WriteLine(hyphenate(text.Substring(0, i))); 
        } 

        static string hyphenate(string s)
        {
            var re = new Regex(@"(\w{4}\B)");
            return re.Replace (s, "$1-");
        }

        static string dehyphenate (string s)
        {
            return s.Replace("-", "");
        }
    } 
}

Solution 3:[3]

var hyphenText = new string(
  text
 .SelectMany((i, ch) => i%4 == 3 && i != text.Length-1 ? new[]{ch, '-'} : new[]{ch})
 .ToArray()

)

Solution 4:[4]

something along the lines of:

public string GetResultsWithHyphen(string inText)
{
    var counter = 0;
    var outString = string.Empty;
    while (counter < inText.Length)
    {
        if (counter % 4 == 0)
            outString = string.Format("{0}-{1}", outString, inText.Substring(counter, 1));
        else
            outString += inText.Substring(counter, 1);
        counter++;
    }
    return outString;
}

This is rough code and may not be perfectly, syntactically correct

Solution 5:[5]

public static string GetResultsWithHyphen(string str) {
  return Regex.Replace(str, "(.{4})", "$1-");
  //if you don't want trailing -
  //return Regex.Replace(str, "(.{4})(?!$)", "$1-");
}

public static string GetResultsWithOutHyphen(string str) {            
  //if you just want to remove the hyphens:
  //return input.Replace("-", "");
  //if you REALLY want to remove hyphens only if they occur after 4 places:
   return Regex.Replace(str, "(.{4})-", "$1");
}

Solution 6:[6]

For removing:

String textHyphenRemoved=text.Replace('-',''); should remove all of the hyphens

for adding

StringBuilder strBuilder = new StringBuilder();
int startPos = 0;
for (int i = 0; i < text.Length / 4; i++)
{
    startPos = i * 4;
    strBuilder.Append(text.Substring(startPos,4));

    //if it isn't the end of the string add a hyphen
    if(text.Length-startPos!=4)
        strBuilder.Append("-");
}
//add what is left
strBuilder.Append(text.Substring(startPos, 4));
string textWithHyphens = strBuilder.ToString();

Do note that my adding code is untested.

Solution 7:[7]

GetResultsWithOutHyphen method

public string GetResultsWithOutHyphen(string input)
{

     return input.Replace("-", "");

}

GetResultsWithOutHyphen method

You could pass a variable instead of four for flexibility.

public string GetResultsWithHyphen(string input)
{

string output = "";
        int start = 0;
        while (start < input.Length)
        {
            char bla = input[start];
            output += bla;
            start += 1;
            if (start % 4 == 0)
            {
                output += "-";    
            }
        }
return output;
}

Solution 8:[8]

This worked for me when I had a value for a social security number (123456789) and needed it to display as (123-45-6789) in a listbox.

ListBox1.Items.Add("SS Number :  " & vbTab & Format(SSNArray(i), "###-##-####"))

In this case I had an array of Social Security Numbers. This line of code alters the formatting to put a hyphen in.

Solution 9:[9]

Callee

public static void Main()
{
    var text = new Text("THISisJUSTanEXAMPLEtext");
    var convertText = text.Convert();
    Console.WriteLine(convertText);
}

Caller

public class Text
{
    private string _text;
    private int _jumpNo = 4;
    
    public Text(string text)
    {
        _text = text;
    }
    
    public Text(string text, int jumpNo)
    {
        _text = text;
        _jumpNo = jumpNo < 1 ? _jumpNo : jumpNo;
    }
    
    public string Convert()
    {
        if (string.IsNullOrEmpty(_text)) 
        {
            return string.Empty;
        }
        
        if (_text.Length < _jumpNo)
        {
            return _text;   
        }
        
        var convertText = _text.Substring(0, _jumpNo);
        int start = _jumpNo;
        while (start < _text.Length)
        {
            convertText += "-" + _text.Substring(start, Math.Min(_jumpNo, _text.Length - start));
            start += _jumpNo;
        }
        
        return convertText;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ria
Solution 2 Reacher Gilt
Solution 3 Serj-Tm
Solution 4 Jonathan
Solution 5
Solution 6 Serj-Tm
Solution 7
Solution 8 MrZander
Solution 9 Choirul Anas