2

如何将以下字符串拆分为单词

string exp=price+10*discount-30

进入

string[] words={'price',discount' }

4

3 回答 3

2

你可以用正则表达式匹配单词,然后得到结果。

例子:

        // This is the input string.
        string input = "price+10*discount-30";

        var matches = Regex.Matches(input, @"([a-z]+)", RegexOptions.IgnoreCase | RegexOptions.Multiline);
        foreach (var match in matches)
        {
            Console.WriteLine(match);
        }
        Console.ReadLine();
于 2012-12-11T14:06:40.930 回答
0

希望这个例子有帮助:

string str = "price+10*discount-30";
char[] delimiters = new char[] { '+', '1', '0', '*', '-', '3'};
string[] parts = str.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in parts)
    Console.WriteLine(s);

Console.ReadLine();

输出是:

price
discount
于 2012-12-11T13:25:47.947 回答
0

你想要的是一个词法分析器,它根据输入的类型对单词进行标记。这是一个为您执行此操作的小程序。

        int dummy;
        string data = "string price = 10 * discount + 12";
        string[] words = data.Split(' ');
        LinkedList<string> tokens = new LinkedList<string>();
        LinkedList<string> keywords = new LinkedList<string>();
        LinkedList<string> operators = new LinkedList<string>();
        keywords.AddLast("string");
        operators.AddLast("*");
        operators.AddLast("/");
        operators.AddLast("+");
        operators.AddLast("=");
        operators.AddLast("-");
        foreach (string s in words)
        {
            if (keywords.Contains(s)) continue;
            if (operators.Contains(s)) continue;
            if (int.TryParse(s, out dummy) == true) continue;
            tokens.AddLast(s.Trim());
        }
        string[] data_split = tokens.ToArray();
于 2012-12-11T13:28:47.197 回答