在 c# 中剪切长单词

本文关键字:单词 | 更新日期: 2023-09-27 18:30:27

我必须用"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;

在 c# 中剪切长单词

如何编写一个扩展方法来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;
}

尽管您的解决方案不是最好的,但为了修复它,您必须在 do-while 语句的开头添加 tempResult = "。另外,请确保还更改了 temp2。子字符串(长度)到 temp2。子字符串(长度 -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

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

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

尝试更简单一些:

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;

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

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- or sit amet, consect- etur adipiscing elit- .Donec blandit ligu- la 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.

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

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

以下方法实现该要求:

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