1

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

例句

敏捷的棕狐跳过了懒狗

它应该成功

敏捷的棕狐跳过了
懒狗

虽然第 37 个字符是“L”

我想按单词分组。

这是我的代码

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

一旦句子是 37 个字符,它就一直在做else。我希望每行在添加之前为 37 \n。仅当句子长于 37 个字符时才会发生这种情况

4

8 回答 8

3

这应该可以解决问题。顺便说一下,为了方便起见,我将使用 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;
}
于 2013-04-03T17:11:14.503 回答
2

您可以像下面那样执行字符串子字符串方法,

 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();
        }
于 2017-07-25T08:29:41.473 回答
2

我用这个:

    /// <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();
    }

它假定没有词长于maxLen

于 2021-02-20T04:18:37.217 回答
0

更正了你的 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
            }
于 2013-04-03T17:06:10.020 回答
0

您可以包含一个记录当前记录的行数的字段:

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 = "";
    }
于 2013-04-03T17:07:39.057 回答
0

添加第一个 \n 后,字符串将始终超过 37 个字符,因此第一个 if(len<37) 测试只会返回一次 true。

相反,您需要另一个变量,即

string tempLine = "";

然后,当您遍历您的单词集合时,通过 tempLine 构建一个由总计 <= 37 个字符的单词组成的行,一旦达到最大值,将其添加到 completedWord,然后在下一个循环之前重置 tempLine = ""。

temp = tempLine + wordArray[i] + ' ';
if (temp.Length < 37)
{
    tempLine = tempLine + wordArray[i] + ' ';
}
else
{
    completedWord = completedWord + tempLine + "\n";
    tempLine = "";
}
temp = "";
于 2013-04-03T17:15:47.073 回答
0

这是我的尝试。它是一个简短的递归函数,接受您希望分成多行的字符串,以及每行的最大长度(截止点)作为参数。

它将输入文本的子字符串从开头获取到所需的行长,并将其添加到“输出”变量中。然后它将输入字符串的剩余部分返回给函数,在该函数中它不断递归调用自身,直到剩余部分的长度小于所需的行长,此时它返回输出变量。

希望这很清楚。

    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;

}
于 2018-07-12T08:20:20.190 回答
0

当前接受的答案过于复杂,不确定是否准确(见评论)。一个更简单和准确的解决方案是:

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

请注意,此解决方案:

  1. 不要在行尾留空格;
  2. 代码更干净。例如,具有更少的条件并且它会提前返回以提高代码准备度

还用单元测试介绍了这个方法,所以你可以看到它是有效的:

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);
    }
}
于 2021-03-23T15:34:30.080 回答