【问题标题】:How to remove a special characters from the parsed string如何从解析的字符串中删除特殊字符
【发布时间】:2018-12-28 01:25:18
【问题描述】:

我正在解析网站上某些商品的价格。但是,我在字符串之前得到了一些不相关的特殊字符。如何删除那些字符和我想要的字符串?

我来了

\n                \n                    \n                    \n                \n\n                \n                    \n                    \n                        AMD YD2600BBAFBOX 3.9GHz Socket AM4 Processor

   17,975.00

但是,我使用 Replace 方法替换了字符串中不需要的特殊字符

itemName = itemNameNode.InnerText.Replace("\n", "");
itemPrice = itemPriceNode.InnerText.Replace("                      ", "Current price:");

我仍然没有得到预期的结果。我得到的结果是

I have linked my image here for reference. It doesn't allow me to post image here (Seriously! stackoverflow)

【问题讨论】:

    标签: c# html-parsing


    【解决方案1】:

    您可以简单地使用String.Trim,而不是替换您的itemName 字符串的换行符。 Trim 删除字符串上所有返回 true 到 char.IsWhiteSpace 调用的前导或尾随字符,其中包括一个换行符。

    var x = "\n   Hello   \n";
    
    Console.WriteLine("-");
    Console.WriteLine(x);
    Console.WriteLine("-");
    /* Output:
    -
    
       Hello   
    
    -
    */
    
    Console.WriteLine("-");
    Console.WriteLine(x.Trim());
    Console.WriteLine("-");
    /* Output:
    -
    Hello
    -
    */
    

    【讨论】:

      【解决方案2】:

      首先,我会这样尝试。

      itemName = itemNameNode.InnerText.Trim();
      itemPrice = itemPriceNode.InnerText.Trim().Replace("  ", "Current price:");
      

      在使用Replace()之前使用Trim()怎么样

      希望对你有帮助。

      【讨论】:

      • 是的,我已经使用“当前价格”来补偿   现在我将我的代码替换为itemPrice = itemPriceNode.InnerText.Trim().Replace("  ", "").Trim(); 感谢您的建议。
      猜你喜欢
      • 1970-01-01
      • 2011-04-11
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多