如何将以下字符串拆分为单词
string exp=price+10*discount-30
到
string[] words={'price',discount' }
答案 0 :(得分: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();
答案 1 :(得分: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
答案 2 :(得分: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();