0

I am building up a string of data using substring. The format of the data I want is

[1,2,3,4,5,6,7,8,9,10]

So I am building it up as follows

StringBuilder sb = new StringBuilder();
sb.append("1,");
sb.append("2,");
sb.append("3,");
.
.
.

The problem I run into is when I want to trim the final , before adding the closing ].

I could do

sb.ToString();
sb.Substring(0, (sb.Length - 1));
sb += "]";

But using the += is not very efficient as this creates a new string. Is there a better way of doing this?

2
  • 3
    and what about opening bracket ? Commented Nov 12, 2012 at 10:12
  • var result = string.Concat("[", string.Join(",", someEnumerable), "]"); is a little faster, and much simpler than a StringBuilder approach, I've tested it. Commented Nov 16, 2012 at 12:15

5 Answers 5

6
var str = "[" + String.Join(", ",Enumerable.Range(1,10)) + "]";
Sign up to request clarification or add additional context in comments.

4 Comments

But it's not what OP has asked for since it creates new strings and it's also not clear that OP wants only integers between 1 and 10 even if it's the sample data.
Thanks for this, I never knew you could do this with link. It would require a re write of my code so i won't use it now, but it is good for the future @L.B
I like this approach even if it is not particularly performance worthy due to the creation of several strings.
@WesleySkeen, you can do it in one line without linq of course, just use String.Format, as in my answer.
4

Don't add the final , if you don't need it:

var sb = new StringBuilder().Append('[');
var first = true;
foreach (var item in collection)
{
    if (first)
        first = false;
    else
        sb.Append(',');
    sb.Append(item);
}
sb.Append(']');
var result = sb.ToString();

9 Comments

This is the most correct suggestion but the wrong code. You have to check for last one, not the first.
@ssg: I add a comma before each element except for the first one. Why is that wrong?
@dtb I thought you added comma after, sorry my bad. Then this is the proper answer.
@dtb this is the right answer. Sorry for my wrong initial interpretation :) +1ed :)
string.Format("[{0}]", string.Join(",", collection)); achieves the same in one line.
|
3

The easiest is to use -= on the StringBuilder's Length since it's writable:

sb.Length -= 1; // removes the last char

6 Comments

Wasn't the question about the +=?
@Jodrell: I'm not sure because the title mentions "using substrings properly" and "The problem I run into is when I want to trim the final , before adding the closing ]".
This may need a check if "[]" is a valid result. Otherwise the opening bracket might get removed.
Setting .Length copies the contents of StringBuilder buffer to another newly created array, it's not much different than Substring approach so definitely not efficient. Try @dtb 's answer.
@ssg: Only if the buffer is not large enough for the new length. Which is not the case if the length is decreased.
|
3

UPDATE

After a little testing

var result = string.Concat("[", string.Join(",", someEnumerable), "]");

is both much simpler and faster than a builder approach


You could always just do

var result = string.Format("[{0}]", string.Join(",", someEnumerable));

The sequence can be anything you want, for instance

var someEnumerable = Enumerable.Range(1, 10);

This seems simpler than reinventing the wheel, and avoids intermediate strings.

This does make assumptions about the implementation of String.Join but, I think you should assume that its good enough for this purpose.


For more information, this Question does a comparison between String.Join and StringBuilder.

This Question indicates that String.Format uses a StringBuilder.

7 Comments

Whilst it was not me that downvoted, the code does not work. It should be string.Join(",", someEnumerable));
Also I do not know if this is creating multiple strings behind the scenes.
@activwerx, doh, fixed the ommited parameter. You are right, I don't know how String.Join is implemented either but, I should assume that its has been provided for a reason.
Well I've removed the downvote as I think this is a good implementation! :-)
Any comments downvoters? that sounded so audacious when you know it why you were. Editing a wrong answer and then questioning back masks nothing. SO is so transparent. While I was one downvoter, I removed it now.
|
1

Here is an example as a nice clean method:

    public static string WriteValues(int start, int end)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("[");
        for (int index = start; index <= end; index++)
        {
            sb.Append(index).Append(",");
        }
        sb.Length -= 1;
        sb.Append("]");
        return sb.ToString();
    }

This does all the work in the StringBuilder and then passes back a single string. Also you can specify the start and end values!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.