1

我正在将一个遗留的 PHP 应用程序迁移到 .net,其中一个要求是 URL 与以前完全一样。

为了生成遗留应用程序使用的友好 URL str_word_count,我想知道这个函数是否有 C# 的端口?

4

1 回答 1

4

好的,这是我的“糟糕的 C#”示例(在混合返回类型中模仿 PHP)。这是一个利用 .NET 正则表达式的相当简单的实现。

private enum WORD_FORMAT
{
    NUMBER = 0,
    ARRAY = 1,
    ASSOC = 2
};

private static object str_word_count(string str, WORD_FORMAT format, string charlist)
{
    string wordchars = string.Format("{0}{1}", "a-z", Regex.Escape(charlist));

    var words = Regex.Matches(str, string.Format("[{0}]+(?:[{0}'\\-]+[{0}])?", wordchars), RegexOptions.Compiled | RegexOptions.IgnoreCase);

    if (format == WORD_FORMAT.ASSOC)
    {
        var assoc = new Dictionary<int, string>(words.Count);
        foreach (Match m in words)
            assoc.Add(m.Index, m.Value);
        return assoc;
    }
    else if (format == WORD_FORMAT.ARRAY)
    {
        return words.Cast<Match>().Select(m => m.Value).ToArray();
    }
    else // default to number.
    {
        return words.Count;
    }
}

因此,如果您选择,该函数将返回 a ,Dictionary<int,string>如果您选择ASSOC,则返回 a,string[]如果您选择,则返回ARRAYsimple 。intNUMBER

一个例子(我在这里复制了 PHP 的例子

static void Main(string[] args)
{
    string sentence = @"Hello fri3nd, you're
   looking          good today!";

    var assoc = (Dictionary<int,string>)str_word_count(sentence, WORD_FORMAT.ASSOC, string.Empty);
    var array = (string[])str_word_count(sentence, WORD_FORMAT.ARRAY, string.Empty);
    var number = (int)str_word_count(sentence, WORD_FORMAT.NUMBER, string.Empty);

    //test the plain array
    Console.WriteLine("Array\n(");
    for (int i = 0; i < array.Length; i++)
        Console.WriteLine("\t[{0}] => {1}", i, array[i]);
    Console.WriteLine(")");
    // test the associative
    Console.WriteLine("Array\n(");
    foreach (var kvp in assoc)
        Console.WriteLine("\t[{0}] => {1}", kvp.Key, kvp.Value);
    Console.WriteLine(")");
    //test the charlist:
    array = (string[])str_word_count(sentence, WORD_FORMAT.ARRAY, "àáãç3");
    Console.WriteLine("Array\n(");
    for (int i = 0; i < array.Length; i++)
        Console.WriteLine("\t[{0}] => {1}", i, array[i]);
    Console.WriteLine(")");
    //test the number
    Console.WriteLine("\n{0}", number);
    Console.Read();
}

但是,我想在这里添加一个注释:不要返回对象。它适用于 PHP,因为它不是强类型语言。确实,您应该编写函数的单独版本以适应每种不同的格式。无论如何,这应该让你开始:)

输出:

Array
(
    [0] => Hello
    [1] => fri
    [2] => nd
    [3] => you're
    [4] => looking
    [5] => good
    [6] => today
)
Array
(
    [0] => Hello
    [6] => fri
    [10] => nd
    [14] => you're
    [25] => looking
    [42] => good
    [47] => today
)
Array
(
    [0] => Hello
    [1] => fri3nd
    [2] => you're
    [3] => looking
    [4] => good
    [5] => today
)

7
于 2012-08-23T18:41:17.690 回答