用/斜杠拆分数组

时间:2012-03-12 19:49:29

标签: c#

来自我的数组字符串中的调试器我得到了这个


" /奔驰/ 190级/ 1993 /"类=" canonicalLink"数据的QString ="子=轿车"> 1993

我希望在每个' /'之后拆分文字。并在string []中获取它,这是我的努力

Queue<string> see = new Queue<string>(); //char[] a = {'\n '};
       List<car_facts> car_fact_list = new List<car_facts>();
       string[] car_detail;
       foreach (string s in car)
       {

           MatchCollection match = Regex.Matches(s, @"<a href=(.+?)</a>",
            RegexOptions.IgnoreCase);

            // Here we check the Match instance.
            foreach(Match mm in match)
            {
                // Finally, we get the Group value and display it.
                string key = mm.Groups[1].Value;
                //key.TrimStart('"');
                //key.Trim('"');
                key.Trim();

                **car_detail = Regex.Split(key, "//");**//I tried with strin.Split as well and tried many combination of seperator ,

                see.Enqueue(key);
            }

}

在car_detail [0]中我得到了这个&#34; $ [link]&#34;&gt; $ [title]

来自此字符串&#34; / mercedes-benz / 190-class / 1993 /&#34;类=&#34; canonicalLink&#34;数据的QString =&#34;子=轿车&#34;&GT; 1993

1 个答案:

答案 0 :(得分:14)

目前尚不清楚为什么你在这里使用双斜杠......

string[] details = key.Split('/');

应该可以正常工作。 (注意,正斜杠必须在C#中进行转义。)例如:

using System;

class Test
{
    static void Main()
    {
        string text = "/mercedes-benz/190-class/1993/";
        string[] bits = text.Split('/');
        foreach (string bit in bits)
        {
            Console.WriteLine("'{0}'", bit);
        }
    }
}

输出:

''
'mercedes-benz'
'190-class'
'1993'
''

空字符串是由前导和斜杠引起的。如果你想避免这些,你可以使用

string[] details = key.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries);

注意:

  • car_facts是C#中非常传统的名称。通常情况下,您会遇到类似CarFacts(或可能仅CarCarInfo等)的内容。同样地,car_fact_list通常是carFactList或类似的东西。

  • 此代码不符合您的预期:

    key.Trim();
    

    字符串在.NET中是不可变的 - 因此Trim()返回对 new 字符串的引用,而不是更改现有字符串的内容。你可能想要:

    key = key.Trim();
    
  • 您当前正在为car_detail分配值,但从不使用它。为什么呢?

  • 一般来说,使用正则表达式解析HTML是一个非常糟糕的主意。考虑使用HTML Agility Pack或类似的东西。