Reputation: 125
I have an array e.g. string[] ccsplit.
I want to add all of these into a string, so I use stringbuilder:
StringBuilder builder = new StringBuilder();
foreach (string str in ccsplit)
{
builder.Append(str);
}
But the only problem is that I don't want the string ccsplit[0] to be added to the stringbuilder, how could I achieve this?
Upvotes: 1
Views: 907
Reputation: 460360
You could also use LINQ to concat all strings:
String result = ccsplit.Skip(1).Aggregate((s1, s2) => s1 + s2);
Edit: Here's a version that uses StringBuilder
:
String result = ccsplit.Skip(1).Aggregate(new StringBuilder(),
(sb, str) => sb.Append(str),
(sb) => sb.ToString());
Upvotes: 2
Reputation: 13343
Change the foreach by a for starting the index at 1 instead of 0
for (int i = 1; i <= ccsplit.Length-1; i++)
{
builder.Append(ccsplit[i]);
}
Upvotes: 0
Reputation: 2179
You probably need a string
in the end, so just use appropriate string.Join
overload instead of StringBuilder
and a loop:
string combined = string.Join(string.Empty, ccsplit, 1, ccsplit.Length - 1);
Upvotes: 1
Reputation: 5150
You can do it like this:
StringBuilder builder = new StringBuilder();
for (int ccsplitIndex = 1; ccsplitIndex < ccsplit.Length; ccsplitIndex++)
{
builder.Append(ccsplit[ccsplitIndex]);
}
Upvotes: 0
Reputation: 48600
One Line Answer
string str = string.Join("", ccsplit.Skip(1).ToArray());
Upvotes: 4
Reputation: 273854
There's not even a need to use a StringBuilder or a loop.
string result = String.Concat(ccsplit.Skip(1));
Will do the job. You do need Fx 4 or later.
Upvotes: 10
Reputation: 5600
Use for loop :
StringBuilder builder = new StringBuilder();
for(int i = 1; i < ccsplit.Length; i++)
{
builder.Append(ccsplit[i]);
}
Upvotes: 0
Reputation: 7817
This is how you could do it without LINQ.
for (var i = 1; i < ccsplit.Length; i++){
builder.Append(ccsplit[i]);
}
Upvotes: 2
Reputation: 7334
You can start the index at 1 all the time and append it to stringbuilder.
for(int i=1; i<lengthOfArray;i++)
{
//Do your stuff.
}
Upvotes: 7
Reputation: 15326
You can use Skip() http://msdn.microsoft.com/en-us/library/bb358985.aspx
StringBuilder builder = new StringBuilder();
foreach (string str in ccsplit.Skip(1))
{
builder.Append(str);
}
Upvotes: 2
Reputation: 97861
using System.Linq;
...
StringBuilder builder = new StringBuilder();
foreach (string str in ccsplit.Skip(1))
{
builder.Append(str);
}
Upvotes: 1
Reputation: 39670
If you can use Linq, you could use the Skip extension method:
foreach (string str in ccsplit.Skip(1))
{
builder.Append(str);
}
or, without Linq:
for (int i = 1; i < ccsplit.Length; i++) {
builder.Append(ccsplit[i]);
}
Upvotes: 3