C# 在特定的开始索引中,检查是否有空格(如果有),删除该空格后的文本并添加“…”&引用;
我有一堆生成的标题文本,它们都有不同的C# 在特定的开始索引中,检查是否有空格(如果有),删除该空格后的文本并添加“…”&引用;,c#,string,replace,substring,C#,String,Replace,Substring,我有一堆生成的标题文本,它们都有不同的.Length,但在字符串的特定起始索引处,我想找到最近的空格,然后删除后面的文本和空格,然后添加“…” 最重要的是它不应该延长49个长度 例如: "What can UK learn from Spanish high speed rail when its crap" 我想确保它成为: "What can UK learn from Spanish high speed rail..." 到目前为止,我创造了 if (item.title.Lengt
.Length
,但在字符串的特定起始索引处,我想找到最近的空格,然后删除后面的文本和空格,然后添加“…”
最重要的是它不应该延长49个长度
例如:
"What can UK learn from Spanish high speed rail when its crap"
我想确保它成为:
"What can UK learn from Spanish high speed rail..."
到目前为止,我创造了
if (item.title.Length >= 49)
{
var trim = item.title.Substring(' ', 49) + "...";
}
但这个可以做以下事情:
"What can UK learn from Spanish high speed rail it..."
这是错误的
我们非常感谢您提供任何帮助或提供任何有关如何实现此目的的提示。这应该在最后一个空间进行修剪,它还可以处理允许部分没有空间的情况:
public static string TrimLength(string text, int maxLength)
{
if (text.Length > maxLength)
{
maxLength -= "...".Length;
maxLength = text.Length < maxLength ? text.Length : maxLength;
bool isLastSpace = text[maxLength] == ' ';
string part = text.Substring(0, maxLength);
if (isLastSpace)
return part + "...";
int lastSpaceIndexBeforeMax = part.LastIndexOf(' ');
if (lastSpaceIndexBeforeMax == -1)
return part + "...";
else
return text.Substring(0, lastSpaceIndexBeforeMax) + "...";
}
else
return text;
}
公共静态字符串TrimLength(字符串文本,int-maxLength)
{
如果(text.Length>maxLength)
{
maxLength-=“…”长度;
maxLength=文本。长度
英国能从西班牙高铁学到什么
给你。如果你有非常大的单词,这个方法可能会失败,但它应该让你开始
public static string Ellipsify(string source, int preferredWidth)
{
string[] words = source.Split(' '); //split the sentence into words, separated by spaces
int readLength = 0;
int stopAtIndex = 0;
for(int i = 0; i < words.Length; i++) {
readLength += words[i].Length; //add the current word's length
if(readLength >= preferredWidth) { //we've seen enough characters that go over the preferredWidth
stopAtIndex = i;
break;
}
readLength++; //count the space
}
string output = "";
for(int i = 0; i < stopAtIndex; i++)
{
output += words[i] + " ";
}
return output.TrimEnd() + "..."; //add the ellipses
}
public静态字符串省略(字符串源,int preferredWidth)
{
string[]words=source.Split(“”);//将句子拆分为单词,用空格分隔
int readLength=0;
int-stopAtIndex=0;
for(int i=0;i=preferredWidth){//我们已经看到足够多的字符超过了preferredWidth
stopAtIndex=i;
打破
}
readLength++;//计算空间
}
字符串输出=”;
对于(int i=0;i
当你说“最近的空格”时,它是与神奇的49号最接近的空格吗?是的,举例来说,字符串长度不应该超过49,这就是为什么它在49号之前取最近的空格很重要