[英]Cut long words in c#
我必須使用“ xxx- xxx”在字符串中剪切任何比長度x長的字符串,以換行。
因此,例如:20個字符是可以的,但是當我的單詞中有30個字符時,我必須將其切為18 +“-” + rest。
我寫了這個方法,它以一個無限循環結束:
string temp = s;
string tempResult = "";
bool found = false;
do
{
found = false;
if (s.Length < lenght) return s;
else
{
//Examine every word to cut everything into words
string[] tempList = temp.Split(' ');
foreach (string temp2 in tempList)
{
//Check every word length now,
if (temp2.Length > lenght)
{
tempResult = tempResult + " " + temp2.Substring(0, lenght - 3) + "- " + temp2.Substring(lenght);
found = true;
}
else
tempResult = tempResult + " " + temp2;
}
if (found) temp = tempResult;
}
} while (found);
return tempResult;
如何為String
編寫擴展方法(考慮單詞邊界)
var s = "abcd defghi abcd defghi".LimitTo(10);
public static string LimitTo(this string s, int maxLen)
{
string toEnd = "...";
if (s.Length > maxLen)
{
maxLen -= toEnd.Length;
while (!char.IsWhiteSpace(s[maxLen])) maxLen--;
s = s.Substring(0, maxLen) + toEnd;
}
return s;
}
但是,您要問的內容還不清楚 ,我想這可能是您想要的,並且更簡單:
static void Main(string[] args)
{
string foo = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec blandit ligula dolor, tristique.";
Console.Write(Truncate(foo, 20));
Console.Read();
}
public static string Truncate(string text, int length)
{
int index = text.Length;
while (index > 0)
{
text = text.Insert(index, "- ");
index -= length;
}
return text;
}
這給出:
Lorem ipsum dol-或坐着,建議使用adipiscing elit-。 多尼斯克·多內克·布蘭迪特·利古拉·多洛爾-
另外,由於不清楚您需要什么,因此產生不同的效果:
static void Main(string[] args)
{
string foo = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec blandit ligula dolor, tristique.";
Console.Write(Truncate(foo, 20));
Console.Read();
}
public static string Truncate(string text, int maxlength)
{
maxlength = maxlength - 2;//allow space for '- '
string truncated = string.Empty;
int lastSpace = 0;
if (text.Length > maxlength)
{
string temp = text.Substring(0, maxlength);
lastSpace = temp.LastIndexOf(" ");
truncated = temp.Substring(0, lastSpace);
}
else
{
return text;
}
return truncated.Trim().Insert(truncated.Length, "- ") + text.Substring(lastSpace);
}
給出:
Lorem ipsum主宰,奉獻自若。 Donec blandit ligula dolor,三位一體。
嘗試一些簡單的方法:
string test = s; //Your string
int count = (int)Math.Floor((decimal) test.Length / 20);
for (int i = 0; i < count; i++)
{
test = test.Insert(((i + 1) * 20), "- ");
}
注意:這是一個基本示例,僅在字符串中每20個字符添加一個"- "
。
編輯-
如果您只想在前20個字符后拼接字符串:
s = s.Length > 20 ? s.Insert(18, "- ") : s;
通過使用擴展方法,您可以隨時輕松地將任何字符串切成任意長度。
public static class MyExtensions
{
public static string CutStringAt(this string s, int length)
{
int len = s.Length;
if (len > length)
{
int pos = 0;
StringBuilder sb = new StringBuilder();
while (pos < len)
{
if ((len - pos) < length)
{
int left = len - pos;
sb.AppendLine(s.Substring(pos, left).Trim());
pos += left;
}
else
{
sb.AppendLine(s.Substring(pos, length).Trim());
pos += length;
}
}
s = sb.ToString();
}
return s;
}
}
使用此代碼,您只需調用即可輕松剪切任何字符串
string aCutString = "This string is waaaaaay tooooo looong".CutStringAt(20);
我不太確定您的要求是什么。 我假設是這樣的:
給定一個字符串,該字符串包含零個或多個用空格分隔的單詞,請插入空格,以使字符串中沒有單詞長於指定字符數。
以下方法實現了該要求:
public string SplitLongWords(string text, int maxWordLength)
{
var result = new StringBuilder();
int currentWordLength = 0;
foreach (char c in text)
{
if (char.IsWhiteSpace(c))
{
currentWordLength = 0;
}
else if (currentWordLength == maxWordLength)
{
currentWordLength = 1;
result.Append(' '); // Or .Append('-') to separate long words with '-'
}
else
{
++currentWordLength;
}
result.Append(c);
}
return result.ToString().TrimEnd();
}
因此,鑒於此輸入:
A AB ABC ABCD ABCDE ABCDEF ABCDEFG ABCDEFGH ABCDEFGHI ABCDEFGHJ
12345678901234567890
輸出將是:
A AB ABC ABCD ABCD E ABCD EF ABCD EFG ABCD EFGH ABCD EFGHI ABCD EFGHJ
1234 5678 9012 3456 7890
盡管您的解決方案不是最佳解決方案,但是要解決此問題,您必須在do-while語句的開頭添加tempResult =“”。 另外,請確保還將temp2.Substring(lenght)更改為temp2.Substring(lenght -3)並修剪最后的字符串,因為它的開頭有空格:
string temp = s;
string tempResult = "";
bool found = false;
do
{
tempResult = "";
found = false;
if (s.Length < lenght) return s;
else
{
//Examine every word to cut everything into words
string[] tempList = temp.Split(' ');
foreach (string temp2 in tempList)
{
//Check every word length now,
if (temp2.Length > lenght)
{
tempResult = tempResult + " " + temp2.Substring(0, lenght - 3) + "- " + temp2.Substring(lenght -3);
found = true;
}
else
tempResult = tempResult + " " + temp2;
}
if (found) temp = tempResult;
}
} while (found);
return tempResult.TrimStart();
您可以簡化解決方案並僅遍歷長單詞,而不是一遍又一遍地構建整個字符串:
protected string test() {
string s = "this is a test for realllllyyyyreallllyyyyloooooooongword";
string temp = s;
int lengthAllowed = 18;
string tempResult = "";
string temp3 = "";
if (s.Length < 18) return s;
else
{
//Untersuche jedes Wort, dazu schneide alles in Wörter
string[] tempList = temp.Split(' ');
foreach (string temp2 in tempList)
{
temp3 = temp2;
//Jetzt jedes Wort auf Länge prüfen,
while (temp3.Length > lengthAllowed)
{
tempResult = tempResult + temp3.Substring(0, lengthAllowed - 3) + "- ";
temp3 = temp3.Substring(lengthAllowed - 3);
}
tempResult = tempResult + temp3 + " ";
}
}
return tempResult.Substring(0,tempResult.Length-1);
}
這是基於以下假設:問題在於如果我們具有以下字符串:
this is a test for realllllyyyyreallllyyyyloooooooongword
結果是:
this is a test for realllllyyyyrea- llllyyyyloooooo- oongword
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.