1.11M Members

C# splitting string in to array

 
1
 

Hello, I am new with c#. I need help in splitting the operators and operand in two different arrays. For example 4+5-3-6+7 is an input string, so in this i want 4,5,3,6,7 in one array and +,- in another array . can anyone please help me out ?

 
0
 

While storing value into your string, put a blank space between each character and then split the string with the help of that space...
you can use this piece of code.

string val = "1 + 2 - 3 + 4";
string[] strSplitArr = val.Split(' ');

you will get all these values in that array.

Hope this helps.....:)

 
0
 

didn't understand that code... can you explain it a bit?

 
1
 

Split is a function of string. But it needs a consistent characater. What Mono was saying was, add a space between each character then you can split on the space character.
You could do it like this

string val = "4+5-3-6+7";
StringBuilder sb = new StringBuilder();
for(int i = 0; i < val.Length; i++)
{
  if (val[i] != ' ')
  {
    sb.Append(val[i]+" ");
  }
  else
    sb.Append(val[i]);
}
string val2 = sb.ToString();
string[] s = val2.Split(' ');

at this point, s is an array of string = {"4","+","5","-","3","-","6","+","7"}
Then you would need to iterate through that array to separate it into two arrays

 
1
 

@mono_jit23: Your code would only split the values into a single array, the OP needs Numbers in one array and operators in another.

@rutul: The problem you are going to have is dimensioning your arrays as you wont know how many Numbers and how many operators your string holds until you have parsed it. I would suggest you use a generic collection like List<string> and List<int> instead as they resize as items are added.

As for splitting it, one approach would be to go character by character using a for loop. If your input only has single digit numbers (0 to 9) then you just check if the current character is a number (char.IsDigit()); if its a number add it to your number list, if its not then add it to your operators.
If the numbers can be greater than 9 then you will need to "remember" the start of the current number then search till you hit an operator to mark the end of the current number before you store it.

Have a go at this yourself and post your code so far if you get stuck :)

 
1
 

This a bit of an implementation as Ryshad suggested. I used the Queu class here, but
List, Stack, or Array class may fit in as well, depending on your needs.

static void Main(string[] args)
        {
            string str = "4+5-3-6+7";
            // make two queus which can hold chars
            Queue<char> NumberQ = new Queue<char>();
            Queue<char> OperatorQ = new Queue<char>();
            // loop through your string one char at the time
            for (int i = 0; i < str.Length; i++) 
            {
                if (char.IsDigit(str[i]))
                {
                    NumberQ.Enqueue(str[i]);// if digit put it in this queu
                }
                else 
                {
                    OperatorQ.Enqueue(str[i]);// else operator, put it in this queu
                }
            }
            // Output the two queues
            Console.WriteLine("Output result for: " + str);
            Console.WriteLine();
            Console.WriteLine("The numbers :");
            int L = NumberQ.Count; // set initial number of elements in number queu
            for (int i = 0; i < L; i++)
            {
                Console.Write(NumberQ.Dequeue()); Console.Write(' ');
            }
            Console.WriteLine();
            Console.WriteLine("The operators :");
            L = OperatorQ.Count; // set initial number of elements in operator queu
            for (int i = 0; i < L; i++)
            {
                Console.Write(OperatorQ.Dequeue()); Console.Write(' ');
            }  
            // realize that the queues are empty at this point!
            Console.ReadKey(); //for debug mode
        }

Succes!

 
0
 

Thank you I got the answer. this will help me a lot

Split is a function of string. But it needs a consistent characater. What Mono was saying was, add a space between each character then you can split on the space character.
You could do it like this

string val = "4+5-3-6+7";
StringBuilder sb = new StringBuilder();
for(int i = 0; i < val.Length; i++)
{
  if (val[i] != ' ')
  {
    sb.Append(val[i]+" ");
  }
  else
    sb.Append(val[i]);
}
string val2 = sb.ToString();
string[] s = val2.Split(' ');

at this point, s is an array of string = {"4","+","5","-","3","-","6","+","7"}
Then you would need to iterate through that array to separate it into two arrays

 
0
 

Just getting my feet wet in LINQ, you could also do it this way:

string str = "4+5-3-6+7";
            // Create the queries.
            var numbers = from char ch in str
                          where char.IsDigit(ch)
                          select ch;
            var operators = from char ch in str
                          where ch=='+' || ch=='-'
                          select ch;
            // Execute the queries.
            foreach (char i in numbers)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();
            foreach (char i in operators)
            {
                Console.Write(i + " ");
            }
            Console.ReadKey(); //for debug mode
 
0
 

If i split the string and put it into a single array then every odd index is filled with a number and even index with signs(+,-,*,/). I don't think it will be so much different than using two separate arrays, rather it will optimize the code. :D

 
0
 

If i split the string and put it into a single array then every odd index is filled with a number and even index with signs(+,-,*,/). I don't think it will be so much different than using two separate arrays, rather it will optimize the code. :D

Arrays start at zero, so each even index would have a number, odd indexes a sign.

 
0
 

that's a silly mistake....... he he:'(

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article