0

我必须用“xxx-xxx”剪切字符串中长度超过 x 的任何字符串以进行换行。

举个例子:20个字符没问题,但是当我的话有30个字符时,我必须把它剪成18个+“-”+休息。

我写了这个方法,最终进入一个无限循环:

 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;
4

6 回答 6

2

写一个扩展方法怎么样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;
}
于 2013-09-06T10:57:08.353 回答
2

但是,您要问的内容非常不清楚,我认为这可能是您想要的,而且要简单得多:

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- 或 sat amet, consectetur adipiscing elit-。Donec blandit ligula dolor, tristique.-

或者,这会产生不同的效果,因为不清楚您需要什么:

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 dolor-sit amet, consectetur adipiscing elit。Donec blandit ligula dolor, tristique。

于 2013-09-06T11:00:08.367 回答
1

尝试一些更简单的东西:

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;
于 2013-09-06T10:49:55.570 回答
1

通过从中制作扩展方法,您可以随时轻松地将任何字符串切割成任何长度。

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);
于 2013-09-06T10:56:28.643 回答
1

我不太确定你的要求是什么。我假设它是这样的:

给定一个包含零个或多个由空格分隔的单词的字符串,插入空格以使字符串中的单词长度不超过指定的字符数。

以下方法实现了该要求:

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
于 2013-09-06T11:00:03.987 回答
1

尽管您的解决方案不是最好的,但为了修复它,您必须在 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
于 2013-09-06T11:11:36.007 回答