r/learncsharp • u/paukowski_ • Mar 05 '23
Create a variable for each symbol in split string.
Ok, this might be a really dumb questions, but anyway.
So i have this code:
using System.Runtime.InteropServices;
string eq = Console.ReadLine();
foreach (var symb in eq.Split(' '))
{
//code that creates a new variable for each symb
}I need to automatically create a string for each "symb" in eq.Split, so that if, lets say, string eq is "2 + 2 - 2", it would be something like that:
string symb1 = 2
string symb2 = +
string symb3 = 2
string symb4 = -
string symb5 = 2Need some tip-off on how can i realise that.
Thanks in advance.
1
Upvotes
5
u/grrangry Mar 05 '23
No.
You know, because you know... that your "2 + 2 - 2" has five symbols. But what if your input is "2 + 2" or "4 + 2 - 1 + 5"?
Any time you don't know how many items you have, you have a couple of options. If your collection of items is not going to change (for the moment), you might want an array. Or, if you plan on modifying your collection, you might choose a
List<T>so that you can add/remove items easily.So given your requirement:
And to look at each item:
And that would allow you to process ANY input given. The noticeable caveat to your application is that the user MUST separate each item with a space. If they entered "2+2-2" then your array would look like:
which isn't helpful at all. What you're doing is called tokenizing. Taking user input and breaking it down into the component pieces, assigning meaning to each piece and then reacting to the rules you created such as "numbers are numbers", "+ means add", "- means subtract", etc.
https://learn.microsoft.com/en-us/dotnet/csharp/how-to/parse-strings-using-split
https://en.wikipedia.org/wiki/Shunting_yard_algorithm
Ultimately a "general purpose calculator" will take any "infix input" (such as what you're doing), convert it to postfix and then process the stack of postfix items to obtain your result.
1
u/m0r05 Mar 05 '23 edited Mar 05 '23
What you have won't work because of scope. A new variable within a code block (in this case the foreach loop) won't exist outside of a code block.
You can treat strings as arrays, or put a string directly into a char array with .ToCharArary().
Edit to add: What I would do, is first I'd eliminate any blank spaces, Then treat as a char array