gpt4 book ai didi

c# - 如何在 C# 中的纯字符串中插入/删除连字符?

转载 作者:太空狗 更新时间:2023-10-29 22:11:01 24 4
gpt4 key购买 nike

我有这样一个字符串;

   string text =  "6A7FEBFCCC51268FBFF";

我有一种方法,我想插入用于在 4 个字符后附加连字符的逻辑 到“文本”变量。所以,输出应该是这样的;

6A7F-EBFC-CC51-268F-BFF

将连字符附加到上面的“文本”变量逻辑应该在这个方法内;

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

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

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

我如何在 C# 中执行此操作(对于桌面应用程序)?执行此操作的最佳方法是什么?提前感谢大家的回答。

最佳答案

GetResultsWithOutHyphen 很简单(应该返回一个 string 而不是 void

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

对于 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('-');
}

关于c# - 如何在 C# 中的纯字符串中插入/删除连字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11437079/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com