【问题标题】:Trim not working on null characters修剪不适用于空字符
【发布时间】:2015-09-17 06:51:29
【问题描述】:

我对修剪方法有一个非常奇怪的问题。我正在尝试修剪从数据库接收到的字符串。这是我目前的方法:

string debug = row["PLC_ADDR1_RESULT"].ToString();
SPCFileLog.WriteToLog(String.Format("Debug: ${0}${1}",debug,Environment.NewLine));
debug = debug.Trim();
SPCFileLog.WriteToLog(String.Format("Debug2: ${0}${1}", debug, Environment.NewLine));
debug = debug.Replace(" ", "");
SPCFileLog.WriteToLog(String.Format("Debug3: ${0}${1}", debug, Environment.NewLine));

产生如下文件输出:

Debug: $    $
Debug2: $    $
Debug3: $    $ 

检查文件中的十六进制代码发现了一些有趣的东西。所谓的空白不是十六进制 20(空白),而是设置为 00(null?)

我们的数据库如何包含此类数据是另一个谜,但无论如何,我需要修剪那些无效 (?) 空字符。我该怎么做?

【问题讨论】:

  • 让我猜你的数据库字符串包含\0字符,第二次分享你如何在数据库数据类型中存储数据+举例说明你如何查询它
  • 数据由我无法控制的另一个服务插入到数据库中。由于 NDA,我不允许透露查询,但可以说它只是 varchar 字段的 SELECT COLUMN。
  • Unicode 代码点为 0x0000 的字符被归类为控制字符,而不是空格。

标签: c# .net sql-server


【解决方案1】:

如果您只想从字符串中删除所有空字符,请尝试以下操作:

debug = debug.Replace("\0", string.Empty);

如果您只想从字符串的末尾删除它们:

debug = debug.Trim('\0');

空字符没有什么特别之处,但它们不被视为空格。

【讨论】:

    【解决方案2】:

    String.Trim() 只是不将 NUL 字符 (\0) 视为空格。最终,它调用this 函数来确定空格,它不会这样对待它。

    坦率地说,我认为这是有道理的。通常\0 不是空格。

    【讨论】:

    • Unicode 将代码点 0x0000 归类为控制字符。
    • @LasseV.Karlsen Christian 的链接显示一些 Unicode 控制字符 被认为是 空格。碰巧\0 不是其中之一:)
    • 很奇怪,他们只硬编码了几个字符,但也许在某个地方也有对CharUnicodeInfo.IsWhitespace 的完整调用。 Char.IsWhitespace 将 65536 个代码点中的 25 个报告为空白。
    • @LasseV.Karlsen 他们预先区分被“检查”为“是空白”的字符是“latin-1”字符(十六进制
    • 好吧,我猜这很有道理。
    【解决方案3】:

    @Will Vousden 让我走上了正轨…… https://stackoverflow.com/a/32624301/12157575

    --但我没有尝试重写或删除该行,而是在点击 linq 语句中以控制字符开头的 StreamReader / StreamWriter 之前过滤掉了行:

    string ctrlChar = "\0"; // "NUL" in notepad++  
    
    // linq statement: "where"
    !line.StartsWith(ctrlChar)  
    // could also easily do "Contains" instead of "StartsWith"
    

    更多上下文:

    internal class Program
    {
        private static void Main(string[] args)
        {
            // dbl space writelines
            Out.NewLine = "\r\n\r\n";
    
            WriteLine("Starting Parse Mode...");
    
            string inputFilePath = @"C:\_logs\_input";
            string outputFilePath = @"C:\_logs\_output\";
            string ouputFileName = @"consolidated_logs.txt";
    
            // chars starting lines we don't want to parse
            string hashtag = "#"; // logs notes
            string whtSpace = " "; // white space char
            string ctrlChar = "\0"; // "NUL" in notepad++
    
    
            try
            {
                var files =
                    from file in Directory.EnumerateFiles(inputFilePath, "*.log", SearchOption.TopDirectoryOnly)
                    from line in File.ReadLines(file)
                    where !line.StartsWith(hashtag) &&
                    !line.StartsWith(whtSpace) &&
                    line != null &&
                    !string.IsNullOrWhiteSpace(line) &&
                    !line.StartsWith(ctrlChar) // CTRL CHAR FILTER
                    select new
                    {
                        File = file,
                        Line = line
                    };
    
                using (StreamWriter writer = new StreamWriter(outputFilePath + ouputFileName, true))
                {
                    foreach (var f in files)
                    {
                        writer.WriteLine($"{f.File},{f.Line}");
    
                        WriteLine($"{f.File},{f.Line}"); // see console
                    }
    
                    WriteLine($"{files.Count()} lines found."); 
                    ReadLine(); // keep console open
                }
            }
            catch (UnauthorizedAccessException uAEx)
            {
                Console.WriteLine(uAEx.Message);
            }
            catch (PathTooLongException pathEx)
            {
                Console.WriteLine(pathEx.Message);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-23
      • 2020-10-26
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多