You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Studio C# String Trim异常求助:无法正确提取数字

Troubleshooting String Trim Failure When Extracting Digits

Hey there! Let's work through why your String.Trim() is acting up—working fine on startup but failing when you need to extract pure digits. Here are some common fixes and checks to try:

  • Watch out for non-standard whitespace characters
    The default Trim() only handles ASCII whitespace (like regular spaces, tabs, newlines). If your string has Unicode whitespace (full-width spaces, non-breaking spaces, etc.), Trim() won't touch them. Instead, use a regex to strip all whitespace or directly keep only digits:

    // Keep only numeric characters
    string digitsOnly = System.Text.RegularExpressions.Regex.Replace(yourInputString, @"[^0-9]", "");
    
    // Or strip all Unicode whitespace first
    string cleanedString = System.Text.RegularExpressions.Regex.Replace(yourInputString, @"\s+", "");
    
  • Check for hidden non-printable characters
    Sometimes strings sneak in control characters (like carriage returns, vertical tabs, or other invisible bytes) that Trim() ignores. To spot these, loop through the string's characters and print their ASCII values:

    foreach (char c in yourInputString)
    {
        Console.WriteLine($"Character: '{c}' | ASCII Code: {(int)c}");
    }
    

    Any codes outside the standard whitespace range (32 for space, 9 for tab, etc.) are likely the culprits.

  • Make sure you're using Trim() correctly
    Remember: strings in C# are immutable. Trim() doesn't modify the original string—it returns a new trimmed one. Double-check you're assigning the result to a variable:

    // Correct: assign the trimmed result to a new variable
    string trimmed = originalString.Trim();
    
    // Wrong: this doesn't change originalString
    originalString.Trim();
    
  • Address the Visual Studio warning
    Even without the screenshot, VS warnings usually hint at issues like null references or invalid operations. If the warning is about possible nulls, add a null check before trimming:

    string safeTrimmed = originalString?.Trim() ?? string.Empty;
    

内容的提问来源于stack exchange,提问作者Erol444

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:39:17