ramesh nune
ramesh nune

Reputation: 53

How to Split string into words in c#

How can I split the following string to words

string exp=price+10*discount-30

into

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

Upvotes: 2

Views: 7081

Answers (3)

yonigozman
yonigozman

Reputation: 707

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

Upvotes: 2

Nikola Crnomarkovic
Nikola Crnomarkovic

Reputation: 81

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

Upvotes: 0

Aniket Inge
Aniket Inge

Reputation: 25695

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

Upvotes: 0

Related Questions