用拆分卡在c#循环上 [英] Stuck on c# loop with split
本文介绍了用拆分卡在c#循环上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个测试字符串1,2,3,4,5,6,7,8,9,10,11,12,13
我希望输出为
123
456
789
101112
13
我不确定slpit的语法。有人可以帮忙吗?
I have a test string "1,2,3,4,5,6,7,8,9,10,11,12,13"
I want the output to be
123
456
789
101112
13
I am not sure of the syntax for slpit. Can someone help?
string strMyTestMessage = "1,2,3,4,5,6,7,8,9,10,11,12,13";
string[] splitted = strMyTestMessage.Split(separator: new[] { "," }, count: 13, options: StringSplitOptions.None);
string strCountTest;
for (int i = 0; i < splitted.Length; i++)
{
if (i / 3 == 1)
strCountTest = splitted[i].ToString() + "\n";
else
strCountTest = splitted[i].ToString();
onsole.WriteLine(strCountTest);
}
推荐答案
拆分选项看起来正确。但是,为了获得预期的输出,您应该以这种方式修改循环:
The split options look correct. However, int order to obtain the expected output you should modify your loop this way:
for (int i = 0; i < splitted.Length; i++)
{
if (i % 3 == 2)
strCountTest = splitted[i].ToString() + "\n";
else
strCountTest = splitted[i].ToString();
Console.Write(strCountTest);
}
试试这个
try this
string strMyTestMessage = "1,2,3,4,5,6,7,8,9,10,11,12,13";
string[] strArray = strMyTestMessage.Split(',');
int iterations = strArray.Length;
for (int i = 0; i <= iterations; )
{
Console.WriteLine(strArray[i] + ((i + 1) < iterations ? strArray[i + 1] : "") + ((i + 2) < iterations ? strArray[i + 2] : ""));
i = i + 3;
}
祝你好运; - )
good luck ;-)
我接受了CPallini322解决方案,因为它是if(i%3 == 2)使用字符串构建器引导我使用自己的解决方案。很抱歉我正在度假的延迟回复。
I accepted CPallini322 solution because it was the if (i % 3 == 2) that lead me to my own solution using string builder. Sorry for the delayed response I was on vacation.
string strMyTestMessage = "1,2,3,4,5,6,7,8,9,10,11,12,13";
string[] splitted = strMyTestMessage.Split(separator: new[] { "," }, count: 13, options: StringSplitOptions.None);
StringBuilder sb = new StringBuilder();
string strOutput;
for (int i = 0; i < 13; i++)
{
strOutput = splitted[i].ToString();
if (i % 3 == 2)
{
sb.Append(strOutput).Append("\n");
strOutput = "";
}
else
{
sb.Append(strOutput);
strOutput = "";
}
}
Console.WriteLine(sb.ToString());
这篇关于用拆分卡在c#循环上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文