2

How can I split the following string to words

string exp=price+10*discount-30

into

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

Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
ramesh nune
  • 53
  • 3
  • 6
  • 2
    Hello, welcome to SO. Please explain in more detail what you want to achieve. It's hard to tell right now what you want to do. – Jakub Konecki Dec 11 '12 at 13:19
  • 3
    Please define what you mean by "words". Are "string" and "exp" not words? Also, is `string exp...` a declaration in C# code? Then why is the right part not a valid string? Or is this your string, as in `string s = "string exp=price+10*discount-30"`? – Thorsten Dittmar Dec 11 '12 at 13:19
  • 1
    How do you define a "word"? It may be possible to solve this problem if you can be clear about such a definition. – Paul Turner Dec 11 '12 at 13:20
  • 1
    There are quite a few examples you may want to look at and try, for example: http://stackoverflow.com/questions/2159026/regex-how-to-get-words-from-a-string-c – dash Dec 11 '12 at 13:22

3 Answers3

2

You could match words with regex and then get the results.

example:

        // 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();
yonigozman
  • 707
  • 8
  • 15
0

Hope this example helps:

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();

Output is:

price
discount
tukaef
  • 9,074
  • 4
  • 29
  • 45
  • if the above is to work with any numbers, then after the forloop you could check for a `Double.TryParse(s)` so that numbers are not read into it. – Vini Jan 21 '16 at 06:25
0

what you want is a lexer, that tokenizes words depending on type of input. Here is a little program that does this for you.

        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();
Aniket Inge
  • 25,375
  • 5
  • 50
  • 78