這個問題在這里已經有了答案: 在 .NET C# 中截斷整個單詞的字串 10 個答案 3 小時前關閉。
例如說我有這個文本字串,大于 70 個字符(包括空格):
“水由氫和氧組成,以氣態、液態和固態存在。水是最豐富和最重要的化合物之一,在正常條件下以液體形式存在于地球表面,這使得它對人類的利用具有不可估量的價值并作為植物和動物的棲息地。”
我只想將此字串縮短到 70 個字符,然后在末尾添加省略號(...)。所以我應用了以下代碼:
public static void MyDescription(string str){
if(str.Length > 70){
str = str.Substring(0,70) "...";
}
Console.Writeline(str);
}
我看到的問題是,它在最后像這樣切割中間的單詞:
"Water is made up of hydrogen and oxygen, and it exists in gaseous, li
相反,我希望它顯示:
Water is made up of hydrogen and oxygen, and it exists in gaseous, liquid
有沒有辦法不斷字補字?
uj5u.com熱心網友回復:
您可以執行以下操作:
if(str.Length > 70) {
// You may want to put this array in a class as a static readonly field
char[] wordEndings = { ' ', ',', '.' };
int endOfWord = str.IndexOfAny(wordEndings, 70);
// It's the last word
if(endOfWord == -1) {
endOfWord = str.Length;
}
str = str.Substring(0, endOfWord);
}
您將需要根據您的用例和一些邊緣情況對其進行更多微調
uj5u.com熱心網友回復:
if (str <= 70) return str;
var words = str.Split(' ');
var charCount = 0;
for (int i = 0; i < words.Length; i ) {
var word = words[i];
charCount = word.Count 1; // 1 for a space
if (charCount > 70) {
// if you don't want to exceed 70, charCount -= word.Length;
break;
}
}
return str.SubString(0, charCount) "...";
這假設至少有 2 個單詞,由“常規”空格字符分隔。如果你沒有空格,這會產生意想不到的結果。如果是這種情況,請在執行上述操作之前檢查是否有任何空格。
uj5u.com熱心網友回復:
該LastIndexOfAny()函式從索引向string. 所以你可以在一行中做到這一點。
return str.Length <= 70 ? str
: str.Substring(0, str.LastIndexOfAny(new [] { ' ', '.', ';' }, 69, 69)) "..."
uj5u.com熱心網友回復:
使用以下課程
public static class StringExtension
{
private const string EllipsisString = "…";
public static string Ellipsis(this string str, int maxChars, bool breakOnNewLine = false) {
string changed = str;
if (breakOnNewLine) {
int newLine = changed.IndexOf('\n');
if (newLine > -1) {
changed = changed.Substring(0, newLine) EllipsisString;
}
}
if (changed.Length > maxChars) {
int lastWordBoundaryInRange = changed.LastIndexOf(' ', maxChars) - 1;
if (lastWordBoundaryInRange < 0) {
lastWordBoundaryInRange = maxChars;
}
changed = changed.Substring(0, lastWordBoundaryInRange);
changed = changed.TrimEnd() EllipsisString;
}
return changed;
}
}
現在在你的課堂上使用
public static void MyDescription(string str){
if(str.Length > 70){
str = str.Ellipsis(70,false);
}
Console.Writeline(str);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/457622.html
標籤:C# 网 。网 asp.net-mvc .net-core
