如果文本太长,我想截断它,但我需要它截断整个单词。我做了以下事情:
var mktText = model.Product.MarketingText;
var countChars = mktText.Length;
if (countChars > 180)
{
countChars = countChars - 180;
mktText = mktText.Remove(180, countChars);
mktText = mktText + "...";
}
此代码将最大字符数设置为 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) + "...";
}
关于c# - 设置字符串的最大长度c#但以整个单词结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16236428/