C# 在特定字数后插入换行符
我想在字符串中的9个单词后插入新行字符(\n),以便第9个单词后的字符串位于下一行 string newline=“如何在(此处)字符串的第九个字后插入换行符,以使剩余字符串位于下一行” 在这里结巴:C# 在特定字数后插入换行符,c#,string,C#,String,我想在字符串中的9个单词后插入新行字符(\n),以便第9个单词后的字符串位于下一行 string newline=“如何在(此处)字符串的第九个字后插入换行符,以使剩余字符串位于下一行” 在这里结巴: foreach (char x in newline) { if (space < 8) { if (x == ' ') { space++; } } }
foreach (char x in newline)
{
if (space < 8)
{
if (x == ' ')
{
space++;
}
}
}
foreach(换行符中的字符x)
{
if(空格<8)
{
如果(x='')
{
空间++;
}
}
}
不知道为什么我会被绊倒。我知道这很简单。如果可能,展示任何其他简单的方法 谢谢大家! 注意:为自己找到了答案。下面由我给出。这是一种方式:
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");
}
}
List\u S=newlist();
var S=“你的句子”.Split().ToList();
对于(int i=0;i
为了体现它的价值,这里有一个LINQ one liner:
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
使用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();
string newline=“如何在(此处)字符串的第九个字后插入换行符,以便剩余字符串位于下一行”;
StringBuilder sb=新的StringBuilder(换行符);
int空间=0;
int长度=sb长度;
for(int i=0;i
在当前代码中,您只是增加空格计数器,而不是将其与
9
进行比较,然后插入新行 你试过插入吗?您还可以使用String.Split(“”)来获取所有单词的数组,顺便说一句。您包含的代码并没有实现您所说的目标,它只计算空格。请包含您尝试的完整代码。此外,请更详细地描述您遇到的错误/问题,以便我们更好地帮助您。通常,要求我们“请给我代码!”的问题会被关闭。如果我们需要插入两个连续的换行符怎么办?然后使用string.Join(Environment.NewLine+Environment.NewLine,
insteadWow。太棒了!这只是在第9个单词后插入一个新行字符,而不是在每个第9个单词后插入一个新行字符,这是需要的吗?另外,如果我使用循环,我会使用StringBuilder
,而不是效率较低的字符串串联。为此,我们可以有:if((空格%9)==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;
}
}