954,546 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

splitting a string and then converting

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 :(

FilteR
Newbie Poster
3 posts since Jul 2007
Reputation Points: 10
Solved Threads: 0
 

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));
            }
CodeMonkey775
Newbie Poster
10 posts since Jul 2007
Reputation Points: 10
Solved Threads: 0
 

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;

tostrinj
Newbie Poster
21 posts since Jul 2007
Reputation Points: 12
Solved Threads: 1
 
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]);

subburaj.r
Newbie Poster
4 posts since May 2007
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You