[英]Insert newline character after specific number of words
我想在我的字符串中的9个单词之后插入一个换行符(\\ n),以便第9个单词后面的字符串在下一行。
string newline =“如何在(这里)字符串的第九个字后插入换行符,以便剩下的字符串在下一行中”
被困在这里:
foreach (char x in newline)
{
if (space < 8)
{
if (x == ' ')
{
space++;
}
}
}
不知道为什么我被卡住了。 我知道这很简单。
如果可能,请显示任何其他简单方法。
谢谢!
注意:找到自己的答案。 由我在下面给出。
对于它的价值,这是一个LINQ单线程:
string newline = "How to insert newline character after ninth word of(here) the string such that the remaining string is in next line";
string lines = string.Join(Environment.NewLine, newline.Split()
.Select((word, index) => new { word, index})
.GroupBy(x => x.index / 9)
.Select(grp => string.Join(" ", grp.Select(x=> x.word))));
结果:
How to insert newline character after ninth word of(here)
the string such that the remaining string is in
next line
这是一种方式:
List<String> _S = new List<String>();
var S = "Your Sentence".Split().ToList();
for (int i = 0; i < S.Count; i++) {
_S.add(S[i]);
if ((i%9)==0) {
_S.add("\r\n");
}
}
使用StringBuilder,如:
string newline = "How to insert newline character after ninth word of(here) the string such that the remaining string is in next line";
StringBuilder sb = new StringBuilder(newline);
int spaces = 0;
int length = sb.Length;
for (int i = 0; i < length; i++)
{
if (sb[i] == ' ')
{
spaces++;
}
if (spaces == 9)
{
sb.Insert(i, Environment.NewLine);
break;
//spaces = 0; //if you want to insert new line after each 9 words
}
}
string str = sb.ToString();
在当前代码中,您只是递增空间计数器,但不将其与9
进行比较,然后插入新行。
你有没有尝试过Environment.NewLine插入? 您还可以使用String.Split(“”)来获取所有单词的数组btw ...
string modifiedLine="";
int spaces=0;
foreach (char value in newline)
{
if (value == ' ')
{
spaces++;
if (spaces == 9) //To insert \n after every 9th word: if((spaces%9)==0)
{
modifiedLine += "\n";
}
else
modifiedLine += value;
}
else
{
modifiedLine += value;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.