ann*_*nna 1 c# string formatting
我想截断文本,如果它太长但我需要它截断整个单词.我做了以下事情:
var mktText = model.Product.MarketingText;
var countChars = mktText.Length;
if (countChars > 180)
{
countChars = countChars - 180;
mktText = mktText.Remove(180, countChars);
mktText = mktText + "...";
}
Run Code Online (Sandbox Code Playgroud)
此代码将最大值设置为180个字符,但会将单词缩减为一半,而不是单词.
任何帮助赞赏.
谢谢
寻找该位置前的最后一个空格,并在那里剪切字符串.如果根本没有空间,或者文本中的内容太快,那么无论如何只需将其剪切为180.
string mktText = model.Product.MarketingText;
if (mktText.Length > 180) {
int pos = mktText.LastIndexOf(" ", 180);
if (pos < 150) {
pos = 180;
}
mktText = mktText.Substring(0, pos) + "...";
}
Run Code Online (Sandbox Code Playgroud)