如何使用c#替换字符串中的字符



我有一个字符串

"这是用于在dotnet4.8(.net(〃中进行测试的测试字符串;53个字符

要求是如果字符串的长度大于40个字符然后将字符替换为""从(.net(开始向左移动,直到总字符数为40,所以我将使用

"This is a test string for testing (.net)"   

如果单词被截断也没关系,因为可能存在字符串不同的scneario,但它们总是以(.net(结尾

如果我理解得对,您希望实际文本为34个字母长,所以在添加您的"(.net(";最后是40岁。

所以我想是在领域

public string Shorten(string s)
{
if(s.Length > 40)
return s.Substring(0,34) + "(.net)";
else
return s;
}

试试这个:

const int maxLength = 40;
const string suffix = "(.net)";
var text = "This is a test string for testing in dotnet4.8 (.net)";
var exceed = text.Length - maxLength;
if (exceed > 0)
{
text = text.Substring(0, text.Length - exceed - suffix.Length) + suffix;
}

您可以使用Regex:

var input = "This is a test string for testing in dotnet4.8 (.net)";
var match = Regex.Match(input, @"^(.{0,34}).*?(.net)$");
var result = $"{match.Groups[1].Value}(.net)";

这给出了CCD_ 2。

最新更新