同一IPv4验证C#代码在Codewars与VS2019运行结果不一致求助
Let's break down why your code works locally but fails on Codewars, and fix the issues step by step:
Key Problems in Your Current Code
Static Variable State Leak
Youripnumberis a static class variable. Codewars runs multiple test cases in sequence, so the value ofipnumberwon't reset between calls. For example, if the first test case passes (setsipnumberto 4), the next test case will start withipnumber = 4instead of 0, leading to false results for subsequent checks.Redundant and Buggy Loop Logic
The lineif (check.Contains('.')) break;is completely unnecessary—your code only adds non-.characters to thechecklist, so this condition will never trigger. Also, appending a.to the input string can lead to unexpected behavior if the original input already ends with a dot (e.g.,"1.2.3.4."becomes"1.2.3.4.."), which might cause extra empty group checks.Implicit Error Handling Gaps
While yourtry/catchhandles invalid number conversions, it doesn't explicitly check for empty groups (like in"1..3.4") or non-digit characters in a more readable way.
Fixed Implementation
Here's a rewritten version that addresses all these issues, with clearer logic that aligns with Codewars' test cases:
using System; namespace IPValidation { class Kata { public static bool is_valid_IP(string ipAddress) { // Split the input by dots string[] octets = ipAddress.Split('.'); // First check: must have exactly 4 octets if (octets.Length != 4) return false; foreach (string octet in octets) { // Check for empty octets or non-digit characters if (string.IsNullOrEmpty(octet) || !IsAllDigits(octet)) return false; // Check for leading zeros (unless the octet is exactly "0") if (octet.Length > 1 && octet.StartsWith("0")) return false; // Convert to integer and check range if (!int.TryParse(octet, out int value) || value < 0 || value > 255) return false; } return true; } // Helper method to check if a string contains only digits private static bool IsAllDigits(string s) { foreach (char c in s) { if (!char.IsDigit(c)) return false; } return true; } } class Program { static void Main(string[] args) { bool num = Kata.is_valid_IP("43.99.196.187"); Console.WriteLine(num); // Should output True Console.ReadKey(); } } }
What This Fixes:
- No Static State: All variables are local to the method, so each test case starts fresh.
- Explicit Length Check: Immediately rejects inputs with too few or too many octets.
- Clear Leading Zero Check: Explicitly disallows octets like
"01"while allowing"0". - Robust Validation: Checks for empty octets and non-digit characters before attempting conversion, making the logic easier to follow and debug.
This should pass all Codewars test cases, including edge cases like empty octets, leading zeros, out-of-range values, and invalid characters.
内容的提问来源于stack exchange,提问作者Andrew Krivalcevich

