When i type in a string consisting of numbers and signs for example:
12 + 3
how can i split it and how can i convert parts of the string into integers?
been searching in the web for 2 hours didnt find anything apropreate :(

Recommended Answers

All 3 Replies

I'm not really sure what you are planning to do with it once you convert it, but this is how you would get the numbers out as integers. To actually evaluate the expression within C#, you would have to delve into CodeDom where you compile C# code during runtime.

string expression = "12 + 3";
            char[] separators = new char[] { Convert.ToChar("+"), Convert.ToChar("-"), Convert.ToChar("*"), Convert.ToChar("/") };

            foreach (string number in expression.Split(separators))
            {
                int convert = Convert.ToInt32(number));
            }

How about this:

string g = "12 + 3";
string[] MyInts = g.Split('+');
ArrayList RealInts = new ArrayList();

for(int i = 0; i < MyInts.Lenght; i++){
   RealInts.Add(Convert.ToInt32(((string)MyInts[i]).Trim());
}

At the end you should get an array list of integers.

RealInts[0] = 12;
RealInts[1] = 3;

If you want individual chars converted into ints then something like this should do it

string g = "12 + 3";

char [] MyInts = g.ToCharArray();
ArrayList RealInts = new ArrayList();

Foreach(char c in MyInts){
  if(IsNumeric(c.ToString())){
    RealInts.Add(Convert.ToInt32(c));
  }
}

After this you should get something like this:

RealInts[0] = 1;
RealInts[1] = 2;
RealInts[2] = 3;

When i type in a string consisting of numbers and signs for example:
12 + 3
how can i split it and how can i convert parts of the string into integers?
been searching in the web for 2 hours didnt find anything apropreate :(

C#
====
string str_string = "12+3";
string[] str_arrstring = str_string.Split('+');
int s_first = Convert.ToInt32(str_arrstring[0]);
int s_second = Convert.ToInt32(str_arrstring[1]);

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.