【问题标题】:C# - Removing white space between characters using the usual techniques don't workC# - 使用常用技术删除字符之间的空格不起作用
【发布时间】:2017-11-25 15:43:34
【问题描述】:

我遇到了一个问题,这似乎是一个真正的问题。我使用HTMLAgilityPack 来读取HTML 页面并使用XPath 来选择我需要的几个元素。这很好用。

使用 XPATH,我也在尝试选择这个 DIV 的数字 (441676)。

<div class="info">
       Money:
       441 676,-<br>        
</div>

我设法选择了数字,并使用这种奇妙的方法对其进行了修剪: Fastest way to remove white spaces in string

但无论我做什么,441 和 676 之间的空白都不会消失。 修剪其他地方的空白就可以了。它仅在数字之间不起作用。有人知道我在这里缺少什么吗?

【问题讨论】:

  • 这个空间的charcode是什么?创建间距的字符不止一个,常用的空格是0x20。
  • 也许它不是“通常的”空白字符,there are many
  • 为什么不在最后阶段试试这个:("441 676").Replace(" ", "");
  • @Rumplin 找不到空格,否则链接方法会起作用。
  • @Rupal:例如只需执行yourstring.ToCharArray().Select(x=&gt;(byte)x).ToArray() 从字符串中获取字节数组并在调试器中查看它。如果是普通空格(十六进制:0x20),则应在相应位置显示 32(十进制为 0x20)。

标签: c# xpath whitespace


【解决方案1】:

在我看来,您正在处理一个不间断的空间。使用您链接的方法,我有两个建议给您。

首先是更新您的toExclude 数组以包含以下字符:

var str = s.ExceptChars(new[] { ' ', '\t', '\n', '\r','\u00A0'});

注意:您可能应该将数组移动到静态全局变量,因为它永远不会改变,而且您不希望每次调用此函数时都重新分配它。

另一种选择是更新您的ExceptChars 函数以使用Char.IsWhiteSpace 函数,如下所示:

public static string ExceptChars(this string str, IEnumerable<char> toExclude) 
{ 
    StringBuilder sb = new StringBuilder(); 
    for (int i = 0; i < str.Length; i++) 
    { 
        char c = str[i]; 
        if (!Char.IsWhiteSpace(c))
            sb.Append(c); 
    } 
    return sb.ToString(); 
} 

【讨论】:

  • 我改用你的解决方案。包括 'u00A0' 解决了问题,而无需像我一样创建新方法。谢谢!
【解决方案2】:

好的,我就是这样解决的。在中使用 exceptChars 方法 Fastest way to remove white spaces in string 我将其修改为仅保留给定字符的“AllowChars”方法。像这样:

public static string AllowedChars(string str, IEnumerable<char> toInclude)
{
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.Length; i++)
        {
            char c = str[i];
            if (toInclude.Contains(c))
                sb.Append(c);
        }
        return sb.ToString();
    }

然后使用这样的方法:

string money_fixed =  AllowedChars(money, new HashSet<char>(new[] {'1','2', '3', '4', '5', '6', '7', '8', '9', '0' }));

【讨论】:

  • 货币可以包含小数点、逗号、连字符和货币符号。
  • 是的,一般来说你是对的,但在这种情况下,数字始终采用 000 000 000 格式,所以我不需要考虑这一点。
猜你喜欢
  • 1970-01-01
  • 2016-12-21
  • 2021-11-16
  • 2021-05-02
  • 2018-03-12
  • 2016-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多