0

文字列の長さ x よりも長い文字列は、"xxx- xxx" で区切り、改行を作成する必要があります。

例: 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

あなたが求めていることは非常に不明確ですが、これはあなたが望むものであり、はるかに簡単だと思います:

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- または sit amet, consectetur 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.

于 2013-09-06T11:00:08.367 に答える
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 に答える
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

あなたの解決策は最善ではありませんが、それを修正するには、do-while ステートメントの先頭に tempResult = "" を追加する必要があります。また、temp2.​​Substring(length) も temp2.​​Substring(length -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 に答える
1

あなたの要件が何であるかはよくわかりません。私はそれがこれであると仮定しています:

スペースで区切られた 0 個以上の単語を含む文字列が与えられた場合、文字列内の単語が指定された文字数より長くならないようにスペースを挿入します。

次のメソッドは、その要件を実装しています。

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

そこから拡張メソッドを作成することで、いつでも任意の文字列を任意の長さに簡単に切断できます。

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 に答える