简体   繁体   English

如果存在超过 37 个字符,如何将字符串拆分为多行

[英]how to split a string into multiple lines if more than 37 characters are present

how to split a string into multiple lines if more than 37 characters are present?如果存在超过 37 个字符,如何将字符串拆分为多行?

Example sentence例句

The Quick Brown Fox Jumped Over The Lazy Dog敏捷的棕狐跳过了懒狗

It should make it它应该做到

The Quick Brown Fox Jumped Over The快速的棕色狐狸跳过了
Lazy Dog懒狗

Although the 37th character is 'L'虽然第 37 个字符是“L”

I want to group by words.我想按单词分组。

Here is my code这是我的代码

private string sentence(string statement)
{
    string completedWord = "";
    string temp = "";
    string[] wordArray = statement.Split(' ');
    for (int i = 0; i < wordArray.Length; i++)
    {
        temp = completedWord + wordArray[i] + ' ';
        if (temp.Length < 37)
        {
            completedWord = completedWord + wordArray[i] + ' ';
        }
        else
        {
            completedWord = completedWord + "\n" + wordArray[i] + ' ';
        }
        temp = "";
    }
    return completedWord;
}

Once the sentence is 37 characters, it keeps doing else .一旦句子是 37 个字符,它就会继续执行else I want each line to be 37 before adding \\n .在添加\\n之前,我希望每一行都是 37。 This only happens if the sentence is much longer than 37 characters仅当句子长于 37 个字符时才会发生这种情况

This should do the trick.这应该可以解决问题。 I'll use the StringBuilder for convenience, by the way.顺便说一下,为了方便起见,我将使用 StringBuilder。

static string sentence(string statement)
{
  if (statement.Length > 37)
  {
    var words = statement.Split(' ');        
    StringBuilder completedWord = new StringBuilder();
    int charCount = 0;

    if (words.Length > 1)
    {
      for (int i = 1; i < words.Length - 1; i++)
      {
        charCount += words[i].Length;
        if (charCount >= 37)
        {
          completedWord.AppendLine();
          charCount = 0;
        }

        completedWord.Append(words[i]);
        completedWord.Append(" ");
      }
    }

    // add the last word
    if (completedWord.Length + words[words.Length - 1].Length >= 37)
    {
      completedWord.AppendLine();
    }
    completedWord.Append(words[words.Length - 1]);
    return completedWord.ToString();
  }
  return statement;
}

You can just do the string substring method as like below,您可以像下面那样执行字符串子字符串方法,

 string WrapText(string statement, int Length)
        {            
            StringBuilder completedWord = new StringBuilder();

            completedWord.Append(statement.Substring(0, Length));//cut the specifed legth from long string
            completedWord.AppendLine();
            completedWord.Append(statement.Substring(Length));//read remainig letters
            return completedWord.ToString();
        }

I use this:我用这个:

    /// <summary>
    /// Wrap lines in strings longer than maxLen by interplating new line
    /// characters.
    /// </summary>
    /// <param name="lines">the lines to process</param>
    /// <param name="maxLen">the maximum length of each line</param>
    public static string[] wrap_lines(string[] lines, int maxLen)
    {
        List<string> output = new List<string>();

        foreach (var line in lines)
        {
            var words = line.Split(' ');
            string newWord = words[0] + " ";
            int len = newWord.Length;

            for (int i = 1; i < words.Length; i++)
            {
                if (len + words[i].Length + 1 > maxLen)
                {
                    len = 0;
                    newWord += "\n";
                    i--;
                }
                else
                {
                    len += words[i].Length + 1;
                    string ch = i == words.Length - 1 ? "" : " ";
                    newWord += words[i] + ch;
                }
            }
            output.Add(newWord);
        }
        return output.ToArray();
    }

It assumes that no word is longer than maxLen .它假设没有单词比maxLen

Corrected your for loop:更正了你的 for 循环:

for (int i = 0; i < wordArray.Length; i++)
            {
                //temp = completedWord + wordArray[i] + ' ';      //remove it
                temp = temp + wordArray[i] + ' ';    //added
                if (temp.Length < 37)
                {
                    completedWord = completedWord + wordArray[i] + ' ';
                }
                else
                {
                    completedWord = completedWord + "\n";    //corrected
                    temp = "";     //added
                }
                //temp = "";       //remove it
            }

You could include a field that records the number of lines currently recorded:您可以包含一个记录当前记录行数的字段:

string completedWord = "";
    string temp = "";
    string[] wordArray = statement.Split(' ');
    int lines = 1;
    for (int i = 0; i < wordArray.Length; i++)
    {

        temp = completedWord + wordArray[i] + ' ';
        if (temp.Length < 37* lines)
        {
            completedWord = completedWord + wordArray[i] + ' ';
        }
        else
        {
            completedWord = completedWord + "\n" + wordArray[i] + ' ';
            lines += 1;
        }
        temp = "";
    }

Once you've added the first \\n, the string will always exceed 37 chars, so the first if(len<37) test will only return true once.添加第一个 \\n 后,字符串将始终超过 37 个字符,因此第一个 if(len<37) 测试将只返回 true 一次。

Instead, you need another var ie相反,你需要另一个变量,即

string tempLine = "";

Then as you iterate over your word collection, build a line composed of words totaling <= 37 chars via tempLine, once you hit the max, add it to completedWord, then reset tempLine = "" before the next loop.然后,当您遍历单词集合时,通过 tempLine 构建由总计 <= 37 个字符的单词组成的行,一旦达到最大值,将其添加到 CompletedWord,然后在下一个循环之前重置 tempLine = ""。

temp = tempLine + wordArray[i] + ' ';
if (temp.Length < 37)
{
    tempLine = tempLine + wordArray[i] + ' ';
}
else
{
    completedWord = completedWord + tempLine + "\n";
    tempLine = "";
}
temp = "";

Here's my go at it.这是我的做法。 Its a short little recursive function accepting the string you wish to break into multiple lines, and the maximum length (the cut off point) of each line, as parameters.它是一个简短的递归函数,接受您希望分成多行的字符串以及每行的最大长度(截止点)作为参数。

It takes a substring of the input text from the beginning to the desired linelength and adds it to an "output" variable.它将输入文本的一个子字符串从开头取到所需的行长,并将其添加到“输出”变量中。 It then feeds the remainder of the input string back in to the function where it keeps recursively calling itself until the length of the remainder is less than the desired linelength, at which point it returns the output variable.然后它将输入字符串的剩余部分送回函数,在那里它不断递归地调用自己,直到剩余部分的长度小于所需的行长,此时它返回输出变量。

Hope that was clear.希望这很清楚。

    public static string breakString(string s, int lineLength){
    string output = "";
    if(s.Length > lineLength){
        output = output + s.Substring(0, lineLength) + '\n';
        string remainder = s.Substring(lineLength, s.Length-lineLength);
        output = output + breakString(remainder, lineLength, maxLines);
    } else {
        output = output + s;    
    }

    return output;

}

The currently accepted answer is overcomplex and not sure if accurate (see comments).当前接受的答案过于复杂,不确定是否准确(见评论)。 A more simple and accurate solution is:一个更简单准确的解决方案是:

public static class StringExtensions
{
    public static string BreakLongLine(this string line, int maxLen, string newLineCharacter)
    {
        // if there is nothing to be split, return early
        if (line.Length <= maxLen)
        {
            return line;
        }

        StringBuilder lineSplit = new StringBuilder();

        var words = line.Split(' ');
        var charCount = 0;
        for (var i = 0; i < words.Length; i++)
        {
            if (charCount + words[i].Length >= maxLen)
            {
                // '>=' and not '>' because I need to add an extra character (space) before the word
                // and last word character should not be cut
                lineSplit.Append(newLineCharacter);
                charCount = 0;
            }

            if (charCount > 0)
            {
                lineSplit.Append(' ');
                charCount++;
            }

            lineSplit.Append(words[i]);
            charCount += words[i].Length;
        }

        return lineSplit.ToString();
    }
}

Please note that this solution:请注意,此解决方案:

  1. do not leave spaces at the end of a line;不要在行尾留空格;
  2. code is cleaner.代码更干净。 For example, has fewer conditions and it returns early to improve code readiness例如,条件较少,并提前返回以提高代码就绪性

I also cover this method with unit tests so you can see that works:还用单元测试介绍了这个方法,所以你可以看到它是有效的:

public class StringExtensionsTests
{
    [Fact]
    public void SplitIntoTwoLines()
    {
        // arrange
        const string longString = "Four words two lines";

        // act
        var resultString = longString.BreakLongLine(10, "\n");

        // assert
        Assert.Equal("Four words\ntwo lines", resultString);
    }

    [Fact]
    public void SplitIntoThreeLines()
    {
        // arrange
        const string longString = "Four words two lines";

        // act
        var resultString = longString.BreakLongLine(9, "\n");

        // assert
        Assert.Equal("Four\nwords two\nlines", resultString);
    }

    // https://stackoverflow.com/questions/15793409/how-to-split-a-string-into-multiple-lines-if-more-than-37-characters-are-present
    [Fact]
    public void StackOverflowExample()
    {
        // arrange
        const string longString = "The Quick Brown Fox Jumped Over The Lazy Dog";

        // act
        var resultString = longString.BreakLongLine(37, "\n");

        // assert
        Assert.Equal("The Quick Brown Fox Jumped Over The\nLazy Dog", resultString);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM