M. Coutinho
M. Coutinho

Reputation: 305

Replace string[] positions

For the next example:

User input sample: "1 + 3 - 2 * 4"

string input = Console.ReadLine();
string[] getElement = input.split(' ');

//So I can have
//getElement[0] = 1
//getElement[1] = +
//getElement[2] = 3
//...

//I have a "for()" cicle here and at one moment I have the following instruction:

if(getElement[i] == "+")
    int add = Convert.ToInt32(getElement[i - 1]) + Convert.ToInt32(getElement[i + 1]);
    //In this example it means: add = 1 + 3

My question is how I can remove positions [0],[1],[2] of my string[] getElement and replace them for "add" value?

I don't know how to use Replace() in this case. Should I need to Resize Array? Need suggestions.

Upvotes: 0

Views: 88

Answers (5)

Jodrell
Jodrell

Reputation: 35716

To address this problem effectively, you'll need to use the Shunting-yard Algorithm to convert your expression to a Reverse Polish Notation representation. That way, you'll obey the BODMAS order of operations and end up with the right result.

Performing the operations, as they are parsed seems easy but will back fire with any resaonably complicated test cases. i.e. whenever the operands appear outside the order of operation. e.g.

3 - 2 + 4 * 2 / ( 2 ^ 2 + 3 )

Upvotes: 0

Milan Raval
Milan Raval

Reputation: 1880

You can do it with

input.Replace(string.Concat(element[0],element[1],element[2]),"Result")

Upvotes: 0

NeverHopeless
NeverHopeless

Reputation: 11233

Try like this:

string input = Console.ReadLine();
string[] getElement = input.split(' ');

if(getElement[i] == "+")
{
    int add = Convert.ToInt32(getElement[i - 1]) + Convert.ToInt32(getElement[i + 1]);
    input = input.Replace(getElement[i - 1] + ' ' + getElement[i] + ' ' + getElement[i + 1]),add.ToString())
}

This will remove all 1+3 from the input expression and replace it with the new value stored under add variable.

Make sure to handle indexOutOfRangeException as suggested by other experts.

Upvotes: 1

Zhafur
Zhafur

Reputation: 1624

Don't use Arrays for it, use Lists. You can't remove and add elements to an array, but you can do it in a List.

List<String> myList = new List<String>();
myList.add("something");
myList.removeAt(0);

Upvotes: 0

Roy Dictus
Roy Dictus

Reputation: 33139

You can use a List<string> instead of an array. You can address individual pieces in a list just like you can in an array, and you can remove items.

Just make sure you test that getElement[i - 1] or getElement[i + 1] will not produce an IndexOutOfRangeException first...

Note: For very simple operations such as those in your example, this is a reasonable approach, but for anything more complicated -- such as support for parentheses or functions -- you'll need to implement a proper parser based on a grammar. You can use the Gold Parsing System to build such a parser (see http://www.goldparser.org).

Upvotes: 2

Related Questions