C#字符串拼接报错:该简单控制台程序为何无法正常运行?
Hey there! Let's walk through the issues in your code that are causing errors and preventing proper string concatenation:
First, here's your code for reference:
using System; namespace ConsoleApp7 { class Program { static void Main(string[] args) { string name; string all; for (int i = 1; i <= 3; i++) { Console.WriteLine("enter name"); name = Console.ReadLine(); Console.WriteLine(name); all = string.Concat(all, name); } Console.WriteLine("all the names are "); // Console.WriteLine(s1); } } }
Key Problems & Fixes:
Uninitialized
allvariable
In C#, reference types likestringdefault tonullwhen declared but not initialized. When you first runstring.Concat(all, name), you're actually concatenatingnullwith your input name—this will result in a string starting with "null" (e.g., if you input "Bob" first,allbecomes "nullBob"). Fix this by initializingallto an empty string:string all = string.Empty; // Or string all = "";Invalid commented output statement
The line// Console.WriteLine(s1);references a variables1that doesn't exist anywhere in your code. Even if you uncomment it, this will throw a compile error. You need to output theallvariable instead to see your concatenated result:Console.WriteLine(all);
Bonus Optimization Tip:
While string.Concat works for small loops, using StringBuilder is more efficient for repeated string operations (since strings are immutable in C#, each concatenation creates a new string object). Here's how you could refactor it:
using System; using System.Text; // Don't forget this namespace! namespace ConsoleApp7 { class Program { static void Main(string[] args) { string name; StringBuilder allNames = new StringBuilder(); for (int i = 1; i <= 3; i++) { Console.WriteLine("enter name"); name = Console.ReadLine(); Console.WriteLine(name); allNames.Append(name); } Console.WriteLine("all the names are: "); Console.WriteLine(allNames.ToString()); } } }
内容的提问来源于stack exchange,提问作者Roee Bloch

