C#字符串转整数数组报错排查及解耦整数求解问题咨询
Fixing Your C# Unique Number Finder Issues
Hey there! Let's walk through fixing your problems step by step. Your core idea using XOR to find the unique (non-duplicate) integer is excellent—great intuition for a beginner! Now let's resolve those errors one by one:
Key Errors & Fixes
- Incorrect Linq Namespace: You tried adding
System.linq, but C# is case-sensitive. The correct namespace isSystem.Linq, which is required to use extension methods likeSelect. - Array Length Typo: Arrays in C# use the
Lengthproperty (capital "L"), notlength—this caused your second error. - Flawed String-to-Array Conversion: Replacing commas with empty strings turns
"1, 2, 3, 1, 2"into"1 2 3 1 2". UsingSelecton this string would iterate over every character (including spaces), leading to invalid integer parsing. Instead, split the string first, clean up each element, then parse.
Corrected Full Code
using System; using System.Linq; // Added correct Linq namespace (case-sensitive!) class Solution { static void Main(String[] args) { int accum = 0; string input = Console.ReadLine(); // Properly convert input string to integer array: int[] num = input.Split(',') .Select(s => s.Trim()) // Remove whitespace from each element .Where(s => !string.IsNullOrWhiteSpace(s)) // Skip empty entries (if any) .Select(int.Parse) // Convert cleaned strings to integers .ToArray(); // Use capitalized Length for array iteration for (int i = 0; i < num.Length; i++) accum ^= num[i]; Console.WriteLine(accum); // Outputs 3 for your test input "1, 2, 3, 1, 2" } }
How the Conversion Works
Split(','): Breaks the input string into an array of substrings at each comma (e.g.,"1, 2"becomes["1", " 2"]).Select(s => s.Trim()): Removes leading/trailing whitespace from each substring (turns" 2"into"2").Where(s => !string.IsNullOrWhiteSpace(s)): Filters out any empty strings that might come from extra commas (like if input ends with,).Select(int.Parse): Converts each cleaned string to an integer.ToArray(): Converts the Linq result into a properint[]array.
Note: You can remove the unused System.Collections.Generic and System.IO using directives to keep your code clean—they aren't needed for this functionality.
内容的提问来源于stack exchange,提问作者Anonymous
相关产品推荐
相关产品推荐

