Bird
Raised Fist0

You want to build a comma-separated list of numbers from 1 to 5 using StringBuilder. Which code snippet is the most efficient and correct?

hard🚀 Application Q15 of Q15
C Sharp (C#) - Strings and StringBuilder
You want to build a comma-separated list of numbers from 1 to 5 using StringBuilder. Which code snippet is the most efficient and correct?
Avar sb = new StringBuilder(); for(int i=1; i<=5; i++) { sb.Append(i).Append(","); } sb.Remove(sb.Length - 2, 1); Console.WriteLine(sb.ToString());
Bvar sb = new StringBuilder(); for(int i=1; i<=5; i++) { sb.Append(i); if(i < 5) sb.Append(","); } Console.WriteLine(sb.ToString());
Cvar sb = new StringBuilder(); sb.Append("1,2,3,4,5,"); Console.WriteLine(sb.ToString());
Dvar sb = new StringBuilder(); for(int i=1; i<=5; i++) { sb.Append(i + ","); } Console.WriteLine(sb.ToString());
Step-by-Step Solution
Solution:
  1. Step 1: Appending comma after each number then removing trailing

    Appends number and comma each time, then removes last comma. Remove call adds overhead.
  2. Step 2: Conditional comma append

    Appends number, then comma only if not last number. Avoids extra Remove call, more efficient and clear.
  3. Step 3: Analyze options B and C

    B appends comma after last number, no removal, so extra comma remains. C hardcodes string, no loop, less flexible.
  4. Final Answer:

    sb.Append(i); if(i < 5) sb.Append(","); -> Option B
  5. Quick Check:

    Append comma conditionally [OK]
Quick Trick: Add comma only between items, not after last [OK]
Common Mistakes:
MISTAKES
  • Leaving trailing comma without removal
  • Hardcoding string instead of looping
  • Removing characters unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes