Reputation: 1844
I need to split a string using any of the operators such as '+' , '-' ,'*', or '/'. How can i append the same to another string while splitting the original one?
For Example : Original string is : Viewer.Amount + Payment - 100
Output : [Viewer.Amount] + [Payment] - 100;
I need to wrap the words with [] and thats why im using split. I choose operators as split characters and i need to append those to my final string.
Please Help . Thank You.
Upvotes: 0
Views: 149
Reputation: 24617
static string Magic(string str)
{
Regex r = new Regex(@"([A-Za-z\.\d]+)");
return r.Replace(str, "[$0]");
}
Output: "[Viewer.Amount] + [Payment] - [100]"
Upvotes: 0
Reputation: 39700
I wouldn't use split if I were you. Instead, use regex replace or maybe just roll your own. A regex to start with: ([A-Za-z\.]+)
Upvotes: 0
Reputation: 881
Maybe this works.
string[] values = providedString.Split({'+', '-', '*' /*etc...*/});
string replaced;
string newString;
for(int i = 0; i < values.Length; i++)
{
if(Int32.TryParse(value[i], out number))
continue;
replaced = "["+values[i]+"]";
newString = providedString.Replace(values[i], replaced);
}
Upvotes: 1
Reputation: 36743
It's not clear what you're trying to do, so you might want to think about editing your question and being more specific.
But if I had to guess, this will help you retrieve the values in your evaluation.
string operation = "[26] + [200] - [100]";
List<string> values = new List<string>();
var items = operation.Split('[');
for (int i = 1; i < items.Length; i++)
{
values.Add(items[i].Substring(0, items[i].IndexOf(']')));
}
foreach (var value in values)
{
Console.WriteLine(value);
}
Console.ReadKey();
So with the above you will retrieve, 26, 200 and 100.
Upvotes: 0