NewBie
NewBie

Reputation: 1844

How to get the split character?

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

Answers (4)

Vasiliy Ermolovich
Vasiliy Ermolovich

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

Ed Marty
Ed Marty

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

Berry Ligtermoet
Berry Ligtermoet

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

Only Bolivian Here
Only Bolivian Here

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

Related Questions