如何在c#中的普通字符串中插入/删除连字符?

Dot*_*mer 5 c# visual-studio winforms

我有这样的字符串;

   string text =  "6A7FEBFCCC51268FBFF";
Run Code Online (Sandbox Code Playgroud)

我有一个方法,我想插入逻辑,用于将4个字符后的连字符附加到'text'变量.所以,输出应该是这样的;

6A7F-EBFC-CC51-268F-BFF
Run Code Online (Sandbox Code Playgroud)

在上面的'text'变量逻辑中添加连字符应该在此方法中;

public void GetResultsWithHyphen
{
     // append hyphen after 4 characters logic goes here
}
Run Code Online (Sandbox Code Playgroud)

我还想删除给定字符串中的连字符,例如6A7F-EBFC-CC51-268F-BFF.因此,从字符串逻辑中删除连字符应该在此方法中;

public void GetResultsWithOutHyphen
{
     // Removing hyphen after 4 characters logic goes here
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能在C#(桌面应用程序)中执行此操作?做这个的最好方式是什么? 提前感谢每个人的回答.

D S*_*ley 7

GetResultsWithOutHyphen很容易(应该返回string而不是void

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

因为GetResultsWithHyphen,可能有更光滑的方法,但这是一种方式:

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('-');
}
Run Code Online (Sandbox Code Playgroud)


Ria*_*Ria 5

使用正则表达式:

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

和移除:

public String GetResultsWithOutHyphen(String inputString)
{
    return inputString.Replace("-", "");
}
Run Code Online (Sandbox Code Playgroud)