我想在我的字符串中的9个单词之后插入一个换行符(\ n),以便第9个单词后面的字符串在下一行。
string newline =“如何在(这里)字符串的第九个单词之后插入换行符,以便剩下的字符串在下一行”
被困在这里:
foreach (char x in newline)
{
if (space < 8)
{
if (x == ' ')
{
space++;
}
}
}
不知道为什么我被困了。我知道这很简单。
如果可能,请显示任何其他简单方法。
谢谢!
注意:为自己找到答案。由我在下面给出。
答案 0 :(得分:12)
对于它的价值,这是一个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
答案 1 :(得分:4)
这是一种方式:
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");
}
}
答案 2 :(得分:1)
使用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
进行比较,然后插入新行。
答案 3 :(得分:0)
您是否尝试过Environment.NewLine插入?您还可以使用String.Split(“”)来获取所有单词的数组btw ...
答案 4 :(得分:0)
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;
}
}