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?
Dvar sb = new StringBuilder();
sb.Append("1,2,3,4,5");
Console.WriteLine(sb.ToString());
Step-by-Step Solution
Solution:
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.
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.
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
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
Master "Strings and StringBuilder" in C Sharp (C#)
9 interactive learning modes - each teaches the same concept differently