如果存在超过 37 个字符,如何将字符串拆分为多行
Posted
技术标签:
【中文标题】如果存在超过 37 个字符,如何将字符串拆分为多行【英文标题】:how to split a string into multiple lines if more than 37 characters are present 【发布时间】:2013-04-03 16:52:05 【问题描述】:?
例句
快速的棕色狐狸跳过了懒狗
应该可以的
快速的棕色狐狸跳过了 懒狗
虽然第 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
。在添加\n
之前,我希望每行都为 37。仅当句子长于 37 个字符时才会发生这种情况
【问题讨论】:
那是什么问题? 一旦句子是 37 个字符,它会继续做 else。在添加 \n 之前,我希望每行都为 37。仅当句子长于 37 个字符时才会发生这种情况 看看这个:codeproject.com/Articles/51488/Implementing-Word-Wrap-in-C 只需要替换2条语句。看看我的回答。 【参考方案1】:这应该可以解决问题。顺便说一下,为了方便,我将使用 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;
【讨论】:
刚刚注意到,它会切断句子中的第一个单词。因为“int i = 1”必须是“int i = 0”。尽管为代码 +1。 如果我错了,请有人纠正我。我认为 charCount charCount += words[i].Length +1; 应该是 +1。我这么说是因为也有空间。我们完全忽略了它。【参考方案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();
【讨论】:
节省了我很多时间。谢谢【参考方案3】:我用这个:
/// <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
。
【讨论】:
【参考方案4】:更正了你的 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
【讨论】:
这只会使第一行 37 个字符或更少。然后基本上你会在每个单词之后添加一个换行符,而不是每 37 个字符。【参考方案5】:您可以包含一个记录当前记录的行数的字段:
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 = "";
【讨论】:
【参考方案6】:添加第一个 \n 后,字符串将始终超过 37 个字符,因此第一个 if(len
相反,您需要另一个变量,即
string tempLine = "";
然后,当您遍历您的单词集合时,通过 tempLine 构建一个由总计
temp = tempLine + wordArray[i] + ' ';
if (temp.Length < 37)
tempLine = tempLine + wordArray[i] + ' ';
else
completedWord = completedWord + tempLine + "\n";
tempLine = "";
temp = "";
【讨论】:
对不起,应该是:string tempLine = "";【参考方案7】:这是我的尝试。它是一个简短的递归函数,接受您希望分成多行的字符串,以及每行的最大长度(截止点)作为参数。
它将输入文本的子字符串从开头到所需的行长,并将其添加到“输出”变量中。然后它将输入字符串的剩余部分返回给函数,在该函数中不断递归调用自身,直到剩余部分的长度小于所需的行长,此时它返回输出变量。
希望这很清楚。
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;
【讨论】:
感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation 将通过展示为什么这是解决问题的好方法,并使其对有其他类似问题的未来读者更有用,从而大大提高其长期价值。请edit您的回答添加一些解释,包括您所做的假设。【参考方案8】:当前接受的答案过于复杂,不确定是否准确(请参阅 cmets)。一个更简单准确的解决方案是:
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();
请注意这个解决方案:
-
不要在行尾留空格;
代码更简洁。例如,具有较少的条件并提前返回以提高代码准备度
我也用单元测试介绍了这个方法,所以你可以看到它有效:
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://***.com/questions/15793409/how-to-split-a-string-into-multiple-lines-if-more-than-37-characters-are-present
[Fact]
public void ***Example()
// 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);
【讨论】:
以上是关于如果存在超过 37 个字符,如何将字符串拆分为多行的主要内容,如果未能解决你的问题,请参考以下文章
如何将包含字符“\ n”的多行字符串拆分为bash中的字符串数组? [复制]