Bird
0
0

You want to build a string by adding numbers from 1 to 5 separated by commas using StringBuilder. Which code snippet correctly does this without extra comma at the end?

hard🚀 Application Q15 of 15
C Sharp (C#) - Strings and StringBuilder
You want to build a string by adding numbers from 1 to 5 separated by commas using StringBuilder. Which code snippet correctly does this without extra comma at the end?
Avar sb = new StringBuilder(); for(int i=1; i<=5; i++) { sb.Append(i + ","); } 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(); for(int i=1; i<=5; i++) { sb.Append("," + i); } Console.WriteLine(sb.ToString());
Dvar sb = new StringBuilder(); sb.Append("1,2,3,4,5"); Console.WriteLine(sb.ToString());
Step-by-Step Solution
Solution:
  1. Step 1: Analyze each option for comma placement

    var sb = new StringBuilder(); for(int i=1; i<=5; i++) { sb.Append(i); if(i < 5) sb.Append(","); } Console.WriteLine(sb.ToString()); adds number then comma only if not last, avoiding trailing comma.
  2. Step 2: Check other options

    var sb = new StringBuilder(); for(int i=1; i<=5; i++) { sb.Append(i + ","); } Console.WriteLine(sb.ToString()); adds comma after every number, causing extra comma at end; C adds comma before number, starting with comma; D hardcodes string, not using loop.
  3. Final Answer:

    var sb = new StringBuilder(); for(int i=1; i<=5; i++) { sb.Append(i); if(i < 5) sb.Append(","); } Console.WriteLine(sb.ToString()); -> Option B
  4. Quick Check:

    Conditionally add commas to avoid trailing one = A [OK]
Quick Trick: Add commas only between items, not after last [OK]
Common Mistakes:
MISTAKES
  • Adding comma after last item
  • Adding comma before first item
  • Hardcoding string instead of looping

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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