How to get [x] and [x+1] into a string then skip to [x+2]
Input : 1 ; a ; 2; b; 3;c;4;d;5;e;6;f
output I'm getting : 1a ; a2;b3;c4;d5;e6
output I want: 1a ; 2b ; 3c; 4d ;开发者_运维百科 5e; 6f
I know this is a simple thing but I just can't seem to get my damn head around it....
Heres my code:
for (int x = 0; x < coll.Count; x++)
{
if (x == 0)
{
line.Append(coll[x].ToString());
line.AppendLine(coll[x + 1].ToString());
}
else
{
if (x % 2 == 0)
{
}
else
{
try
{
line.Append(coll[x].ToString());
line.AppendLine(coll[x + 1].ToString());
x++;
textBox1.Text = line.ToString();
}
catch { }
}
}
If you want to keep the code the way it is (I'm assuming something will go in the empty conditional), then you just need to change if (x % 2 == 0)
to if (x % 2 != 0)
(or equally if (x % 2 == 1)
), as your code is currently appending to the line when i = 0, then 1, 3,... i.e. all odd numbered indices, whereas you need to be appending to the line at all even numbered indices.
(Unfortunately I can't edit your question, but if you just stick four spaces in front of the line starting with for
then it should be formatted correctly.)
If your list is like = [1,a,2,b,3,c,4,d,5,e,6,f] Try this;
String line = "";
for(int i=0;i<list.size();i+2){
line += list.get(i)+list.get(i+1);
}
textBox1.Text = line;
EDIT And if you want semi colons;
I edited like
String line = "";
for(int i=0;i<list.size();i+2){
line += list.get(i)+list.get(i+1);
if(i != list.size() - 2){
line+=";";
}
}
textBox1.Text = line;
One line code with LINQ (but not so efficient):
string[] source = { "1", "a", "2", "b", "3", "c" };
var result = source.Zip(source.Skip(1), (s1, s2) => s1 + s2)
.Where((s, i) => i % 2 == 0);
string[] arrayResult = result.ToArray();
string stringResultWithSeperator = string.Join(";", result);
Another LINQy solution:
string input = "1;a;2;b;3;c;4;d;5;e;6;f";
var split = input.Split(';');
string rejoined = String.Join(";", Pairs(split));
Where Pairs
is
IEnumerable<string> Pairs(IEnumerable<string> strings)
{
if (strings.Take(1).Count() == 0)
{
return new string[]{};
}
return new [] {String.Join("", strings.Take(2))}.Concat(Pairs(strings.Skip(2)));
}
精彩评论