Sign in to follow this  
GraySnakeGenocide

Building a calculator in C#, stuck on doing the math stuff.

Recommended Posts

[quote name='Bill Fountaine' timestamp='1341036908' post='4954218']
I think I am just going to stop while I'm ahead so I don't make myself look any more incompetent than I already have.[/quote]

I must say, your attitude seems very defeatist.

[quote]Obviously the concept of "program, don't just look at tutorials that teaches you how to use stuff." isn't doing anything for me.[/quote]

But that's what programming is. You'll never learn if you don't think for yourself.

I reiterate - post the exact sequence of steps that you want to do and we'll help you find the syntax to carry them out. If you know what you want to do and it's only the syntax that escapes you, then you should have no trouble doing this. If you're having trouble doing that, then clearly it is [i]not[/i] just the syntax you're really having trouble with. What little you've told us is not enough - you're on the right track, but you need to break the problem down further before you get to the level where syntax matters. With that said, I'm going to give you a hint you may find useful in the form of some sample code.

[code]
// starting expression
string expr = "1 + 2";

// see http://msdn.microsoft.com/en-us/library/b873y76a.aspx for documentation on precisely how Split() works
string[] tokens = expr.Split(' ');

// exercise: what will get printed to the screen?
foreach (string t in tokens)
System.Console.WriteLine(t);
[/code]

[quote]The tutorials I have been watching lately, which have me jumping straight into windows forms, are the ones from [url="http://thenewboston.org/list.php?cat=15"]http://thenewboston....list.php?cat=15[/url][/quote]

Which of those tutorials have you watched?

[quote]
Problem solving is easy. I just need to learn the ins and outs of the language to know what syntax I can use to solve said problems.
[/quote]

You will find as you program more and more complicated things that the syntax is actually the easy part, and the problem solving the hard part. Edited by Oberon_Command

Share this post


Link to post
Share on other sites
TextBox.Text
int.TryParse
MessageBox.Show

Google each of them for examples. Try the examples out in your code. Watch what they do.


Here is your quiz:

[code]
string s = ???; // get it from your textbox.
int value;
???; // replace the ??? to convert the string to an integer. Show a messagebox with an error if it fails.
value = value * 5;
// put the resulting value back in the textbox.
[/code] Edited by Nypyren

Share this post


Link to post
Share on other sites
[quote name='Oberon_Command' timestamp='1341038520' post='4954222']
[quote name='Bill Fountaine' timestamp='1341036908' post='4954218']
I think I am just going to stop while I'm ahead so I don't make myself look any more incompetent than I already have.[/quote]

I must say, your attitude seems very defeatist.

[quote]Obviously the concept of "program, don't just look at tutorials that teaches you how to use stuff." isn't doing anything for me.[/quote]

But that's what programming is. You'll never learn if you don't think for yourself.

I reiterate - post the exact sequence of steps that you want to do and we'll help you find the syntax to carry them out. If you know what you want to do and it's only the syntax that escapes you, then you should have no trouble doing this. If you're having trouble doing that, then clearly it is [i]not[/i] just the syntax you're really having trouble with. What little you've told us is not enough - you're on the right track, but you need to break the problem down further before you get to the level where syntax matters. With that said, I'm going to give you a hint you may find useful in the form of some sample code.

[code]
// starting expression
string expr = "1 + 2";

// see http://msdn.microsoft.com/en-us/library/b873y76a.aspx for documentation on precisely how Split() works
string[] tokens = expr.Split(' ');

// exercise: what will get printed to the screen?
foreach (string t in tokens)
System.Console.WriteLine(t);
[/code]

[quote]The tutorials I have been watching lately, which have me jumping straight into windows forms, are the ones from [url="http://thenewboston.org/list.php?cat=15"]http://thenewboston....list.php?cat=15[/url][/quote]

Which of those tutorials have you watched?

[quote]
Problem solving is easy. I just need to learn the ins and outs of the language to know what syntax I can use to solve said problems.
[/quote]

You will find as you program more and more complicated things that the syntax is actually the easy part, and the problem solving the hard part.
[/quote]

I've watched up to vid 18, but I know about some of the other stuff in the other videos.

As for the code itself, I'll get back to that in a bit. I need to get some coffee in me and wake up fully first.

Share this post


Link to post
Share on other sites
If your not acquainted with the idea of reading books on the subject of C# such as in this case. I recommend you start, it would give you exactly what you want if you can find the right book. Examples along with "problem sets" that you can solve to further your skills which is what it sounds like your looking for. Such as [url="http://www.amazon.com/Head-First-2E-Real-World-Programming/dp/1449380344/"]Head First C#, 2E: A Learner's Guide to Real-World Programming with Visual C# and .NET[/url]


Links that might help:
[url="http://www.c-sharpcorner.com/Beginners/"]http://www.c-sharpcorner.com/Beginners/[/url]
[url="http://www.homeandlearn.co.uk/csharp/csharp.html"]http://www.homeandlearn.co.uk/csharp/csharp.html[/url]
[url="http://www.fincher.org/tips/Languages/csharp.shtml"]http://www.fincher.org/tips/Languages/csharp.shtml[/url]

Share this post


Link to post
Share on other sites
[quote name='DevLiquidKnight' timestamp='1341047074' post='4954253']
If your not acquainted with the idea of reading books on the subject of C# such as in this case. I recommend you start, it would give you exactly what you want if you can find the right book. Examples along with "problem sets" that you can solve to further your skills which is what it sounds like your looking for. Such as [url="http://www.amazon.com/Head-First-2E-Real-World-Programming/dp/1449380344/"]Head First C#, 2E: A Learner's Guide to Real-World Programming with Visual C# and .NET[/url]


Links that might help:
[url="http://www.c-sharpcorner.com/Beginners/"]http://www.c-sharpco....com/Beginners/[/url]
[url="http://www.homeandlearn.co.uk/csharp/csharp.html"]http://www.homeandle...arp/csharp.html[/url]
[url="http://www.fincher.org/tips/Languages/csharp.shtml"]http://www.fincher.o...es/csharp.shtml[/url]
[/quote]

but I have stated I have a million books on the subject..including the one you provided. I will go through the tutorials on the sites you provided. I know about csharpcorner but never really did the stuff on it.

Share this post


Link to post
Share on other sites
I made this just for u [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

[source lang="csharp"]using System;
using System.Collections.Generic;

namespace TestAppForGameDev
{
class Program
{
static List<Calculation> calculation = new List<Calculation>();
static void Main(string[] args)
{
Console.Write("Set a inital value to multiply/add/minus/divide from: ");
string inital_string = Console.ReadLine();
double initalvalue = double.Parse(inital_string);
string calculationappearance = inital_string;
Console.WriteLine("Add more values using /add, /minus, /divide or /multiply.");
Console.WriteLine("Use /calc to calculate the answer!");
while (true)
{
string input_string = Console.ReadLine();
string[] input_string_split = input_string.Split(' '); //separate the type of cmd to the specified cmd data, string[] is a array.
if (input_string_split[0] == "/add")
{
calculation.Add(new Calculation(double.Parse(input_string_split[1]), Calculation.Type.Add));
calculationappearance += " + " + input_string_split[1];
}
else if (input_string_split[0] == "/minus")
{
calculation.Add(new Calculation(double.Parse(input_string_split[1]), Calculation.Type.Minus));
calculationappearance += " - " + input_string_split[1];
}
else if (input_string_split[0] == "/divide")
{
calculation.Add(new Calculation(double.Parse(input_string_split[1]), Calculation.Type.Divide));
calculationappearance += " / " + input_string_split[1];
}
else if (input_string_split[0] == "/multiply")
{
calculation.Add(new Calculation(double.Parse(input_string_split[1]), Calculation.Type.Multiply));
calculationappearance += " * " + input_string_split[1];
}
else if (input_string_split[0] == "/calc" || input_string_split[0] == "/calculate")
{
Console.WriteLine("Calculating " + calculationappearance);
double result = initalvalue;
for (int i = 0; i < calculation.Count; i++)
{
switch (calculation[i].type)
{
case Calculation.Type.Add:
result += calculation[i].value;
break;
case Calculation.Type.Minus:
result -= calculation[i].value;
break;
case Calculation.Type.Multiply:
result *= calculation[i].value;
break;
case Calculation.Type.Divide:
result /= calculation[i].value;
break;
}
}
Console.WriteLine("Result: " + result.ToString());
Console.ReadLine(); //make sure user can see result
break; //get out of the while loop and close the program
}
}
}
}
class Calculation
{
public enum Type { Add, Minus, Divide, Multiply }
public double value;
public Type type;
public Calculation(double value, Type type)
{
this.value = value;
this.type = type;
}
}
}
[/source]
Mess around with it, change things around, look up what the List is that is in the source here on MSDN, look up enums too, there are code examples everywhere on there. I hope i helped... Edited by Xanather

Share this post


Link to post
Share on other sites
I did a little searching around, and ended up finding exactly what I was looking for in terms of code to learn from.

[source lang="csharp"]using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

string sOperator = "";
string sFirstValue = "";

private void button0_Click(object sender, EventArgs e)
{
textBox1.Text += button0.Text;
}

private void button1_Click(object sender, EventArgs e)
{
textBox1.Text += button1.Text;
}

private void button2_Click(object sender, EventArgs e)
{
textBox1.Text += button2.Text;
}

private void button3_Click(object sender, EventArgs e)
{
textBox1.Text += button3.Text;
}

private void button4_Click(object sender, EventArgs e)
{
textBox1.Text += button4.Text;
}

private void button5_Click(object sender, EventArgs e)
{
textBox1.Text += button5.Text;
}

private void button6_Click(object sender, EventArgs e)
{
textBox1.Text += button6.Text;
}

private void button7_Click(object sender, EventArgs e)
{
textBox1.Text += button7.Text;
}

private void button8_Click(object sender, EventArgs e)
{
textBox1.Text += button8.Text;
}

private void button9_Click(object sender, EventArgs e)
{
textBox1.Text += button9.Text;
}

private void buttonAdd_Click(object sender, EventArgs e)
{
sFirstValue = textBox1.Text;

textBox1.Text = String.Empty;

sOperator = buttonAdd.Text;
}

private void buttonSubtract_Click(object sender, EventArgs e)
{
sFirstValue = textBox1.Text;

textBox1.Text = String.Empty;

sOperator = buttonSubtract.Text;
}

private void buttonMultiply_Click(object sender, EventArgs e)
{
sFirstValue = textBox1.Text;

textBox1.Text = String.Empty;

sOperator = buttonMultiply.Text;
}

private void buttonDivide_Click(object sender, EventArgs e)
{
sFirstValue = textBox1.Text;

textBox1.Text = String.Empty;

sOperator = buttonDivide.Text;
}

private void buttonEquals_Click(object sender, EventArgs e)
{
float result = 0;

switch (sOperator)
{
case "+":
result = float.Parse(sFirstValue) + float.Parse(textBox1.Text);
break;
case "-":
result = float.Parse(sFirstValue) - float.Parse(textBox1.Text);
break;
case "*":
result = float.Parse(sFirstValue) * float.Parse(textBox1.Text);
break;
case "/":
result = float.Parse(sFirstValue) / float.Parse(textBox1.Text);
break;
}
textBox1.Text = String.Empty;

textBox1.Text = Convert.ToString(result);
}

private void buttonClear_Click(object sender, EventArgs e)
{
textBox1.Text = String.Empty;
}
}
}
[/source]

Edit: I take it back, the code doesn't do what I'm looking for, I thought it did. It only does it after you hit =. Otherwise, you can only add two numbers. Edited by Bill Fountaine

Share this post


Link to post
Share on other sites
Your confusing two distinct issues. There is the programs user interface, and its internal implementation. You are focussing on the user interface, and this is causing the internal implementation to become more complex.

You do not need to parse strings to do this. The strings could instead be inferred from some program state (in a more convenient format for computation).

Let us think about the operations you are exposing, while ignoring the interface. The user can use the 10 digits, and the 4 standard operators. Finally, there is a way to evaluate this. Let us design this system in English.

If we ignore operator precedence, we can model this simply as two lists - a list of numbers and a list of operators. There must always be at least as many numbers as operators, but there can be one more. We use a state machine to determine what should happen if the user presses a button.

If the user presses a digit:
[list]
[*] If there as many operators as numbers, then append this digit to the numbers list.
[*] If there are more numbers than operators, if the user presses a digit then multiple the last number by ten and add the digit.
[/list]
You should eventually handle overflow, but this will suffice for the moment.

If the user presses an operator:
[list]
[*] If there are less operators than numbers, then append the operator the user pressed.
[*] If there as many operators as numbers then replace the last operator with the one the user wants.
[/list]

If the user tries to evaluate:
[list]
[*] If the lists are empty, then display an error (or do nothing).
[*] If there are as many operators as numbers, then display an error (we need a final number to match the last operator).
[*] If there are less operators than numbers, then iterate over both lists, using an accumulator set from the first number, and applying each operator to the accumulator and operator in turn.
[/list]

Psuedo-code for this might look like;
[code]
enumeration Operator {
Plus, Minus, Multiply, Divide
}

type Calculator {

function digit(number x)

function operator(Operator operator)

function evaluate() -> number or Error
}
[/code]

There is one missing piece - and that is allowing the U.I. to present the current state of the program. We can provide a function which will built a string representation of the expression string. You'll need to figure out how to translate this into a C# class. The key point is that the user interface is now decoupled from the internal representation.

You don't need to parse current string - the string is a textual representation of the program's state. By storing the program's state as a string, you are actually throwing away information that you knew as the string was being built.

Share this post


Link to post
Share on other sites
Ok, after thinking over a little bit, I think I at least have the ball rolling. I managed to figure out a way to store the numbers without the math signs. I don't have any of the adding/subtracting/multiplying/dividing logic in yet. Still gotta figure that one out:

[source lang="csharp"]using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

List<string> numbers = new List<string>();
string currentString = "";
char[] mathSymbols = { '+', '-', '*', '/',' '};

private Boolean lastCharIsSymbol { get; set; }

bool add = false;
bool subtract = false;
bool multiply = false;
bool divide = false;

private void button0_Click(object sender, EventArgs e)
{
textBox1.Text += button0.Text;
lastCharIsSymbol = false;
}

private void button1_Click(object sender, EventArgs e)
{
textBox1.Text += button1.Text;
lastCharIsSymbol = false;
}

private void button2_Click(object sender, EventArgs e)
{
textBox1.Text += button2.Text;
lastCharIsSymbol = false;
}

private void button3_Click(object sender, EventArgs e)
{
textBox1.Text += button3.Text;
lastCharIsSymbol = false;
}

private void button4_Click(object sender, EventArgs e)
{
textBox1.Text += button4.Text;
lastCharIsSymbol = false;
}

private void button5_Click(object sender, EventArgs e)
{
textBox1.Text += button5.Text;
lastCharIsSymbol = false;
}

private void button6_Click(object sender, EventArgs e)
{
textBox1.Text += button6.Text;
lastCharIsSymbol = false;
}

private void button7_Click(object sender, EventArgs e)
{
textBox1.Text += button7.Text;
lastCharIsSymbol = false;
}

private void button8_Click(object sender, EventArgs e)
{
textBox1.Text += button8.Text;
lastCharIsSymbol = false;
}

private void button9_Click(object sender, EventArgs e)
{
textBox1.Text += button9.Text;
lastCharIsSymbol = false;
}

private void buttonAdd_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || lastCharIsSymbol)
return;
else
{
textBox1.Text += buttonAdd.Text;
currentString = textBox1.Text;
currentString.TrimEnd(mathSymbols);
numbers.Add(currentString);
lastCharIsSymbol = true;
add = true;
}
}

private void buttonSubtract_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || lastCharIsSymbol)
return;
else
{
textBox1.Text += buttonSubtract.Text;
currentString = textBox1.Text;
currentString.TrimEnd(mathSymbols);
numbers.Add(currentString);
lastCharIsSymbol = true;
subtract = true;
}
}

private void buttonMultiply_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || lastCharIsSymbol)
return;
else
{
textBox1.Text += buttonMultiply.Text;
currentString = textBox1.Text;
currentString.TrimEnd(mathSymbols);
numbers.Add(currentString);
lastCharIsSymbol = true;
multiply = true;
}
}

private void buttonDivide_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || lastCharIsSymbol)
return;
else
{
textBox1.Text += buttonDivide.Text;
currentString = textBox1.Text;
currentString.TrimEnd(mathSymbols);
numbers.Add(currentString);
lastCharIsSymbol = true;
divide = true;
}
}

private void buttonClear_Click(object sender, EventArgs e)
{
textBox1.Text = String.Empty;
}

private void buttonEquals_Click(object sender, EventArgs e)
{
if (add)
{

}

if (subtract)
{

}

if (multiply)
{

}

if (divide)
{

}
}
}
}[/source]

basically, I created a char array, involving the math symbols + whitespace; I trim that off the end, and then store that value into the List.

One thing occured to me just as I thought I got this. This isn't going to just keep adding on the numbers that were already in the textbox, to a new list slot will it?

For example, say you put 25 as the first number, that gets stored, then you hit + or w/e and put 86.

First list slot: 25
Second list slot: This won't be 2586 will it? Thats what concerns me.

EDIT: Close topic please, I can already see that this is going to be dead wrong. So I give up Edited by Bill Fountaine

Share this post


Link to post
Share on other sites
[quote name='Bill Fountaine' timestamp='1341064179' post='4954311']
First list slot: 25
Second list slot: This won't be 2586 will it? Thats what concerns me.[/quote]

With the way you have it right now, it almost will, but it won't. Let's look at the code to see why. Here's a snippet from the code you just posted.

[source]

if (textBox1.Text == "" || lastCharIsSymbol)
return;
else
{
textBox1.Text += buttonMultiply.Text;
currentString = textBox1.Text;
currentString.TrimEnd(mathSymbols);
numbers.Add(currentString);
lastCharIsSymbol = true;
multiply = true;
}
[/source]

Firstly, String.TrimEnd() doesn't actually modify the string. It returns a [i]copy[/i] of the string with whatever characters are in mathSymbols trimmed off. This is because in C#, strings are [i]immutable[/i]. Practically speaking, this means that once a string object has a value, you CANNOT change it without creating a new string, so whenever you call a string method you want to take the return value of that method and use that instead of the original string object. Because of this, with the code you have now, you're actually adding the entire contents of the textbox, [i]including[/i] the math symbols, to the number list! So let's change that TrimEnd() call to this:

[source]

currentString = textBox1.Text.TrimEnd(mathSymbols);
[/source]

Secondly, TrimEnd() will get you what you want, almost. You're correct in observing that with things the way it is right now, if you have "25 + 86", you'll get "2586," which is close but isn't quite what you want. This actually has a pretty easily solution - don't trim whitespace! Consider that because you've included ' 'in your list of "math symbols", all the spaces between the numbers will get trimmed. So let's stop doing that by changing our definition of mathSymbols to this:

[source]

char[] mathSymbols = { '+', '-', '*', '/'};
[/source]

In actual fact, this array better matches its name - it's a list of math symbols, not a list of math symbols and the space character.

Now when that code is run, currentString should contain "25 86". Now, I've already presented a string method in my last post [url="http://www.gamedev.net/topic/627187-building-a-calculator-in-c-stuck-on-doing-the-math-stuff/page__view__findpost__p__4954222"]here[/url] that can split up a string into an array of sub-strings...

[quote]
EDIT: Close topic please, I can already see that this is going to be dead wrong. So I give up
[/quote]

You're doing decently so far. Who cares if it's dead wrong for now? That's how you learn - by making mistakes, learning why they're mistakes, and fixing them. Do you want to learn to program or not? If you can't handle being wrong once in a while, you must have trouble learning [i]anything[/i], never mind programming. I get that this is frustrating you, but if you want to accomplish anything you need to push past the frustration and keep trying. Edited by Oberon_Command

Share this post


Link to post
Share on other sites
So I fixed up the code, but instead of 25 86 it just shows 25 + in the message box.

[source lang="csharp"]using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<string> numbers = new List<string>();
string currentString = "";
char[] mathSymbols = { '+', '-', '*', '/'};

private Boolean lastCharIsSymbol { get; set; }

bool add = false;
bool subtract = false;
bool multiply = false;
bool divide = false;

private void button0_Click(object sender, EventArgs e)
{
textBox1.Text += button0.Text;
lastCharIsSymbol = false;
}

private void button1_Click(object sender, EventArgs e)
{
textBox1.Text += button1.Text;
lastCharIsSymbol = false;
}

private void button2_Click(object sender, EventArgs e)
{
textBox1.Text += button2.Text;
lastCharIsSymbol = false;
}

private void button3_Click(object sender, EventArgs e)
{
textBox1.Text += button3.Text;
lastCharIsSymbol = false;
}

private void button4_Click(object sender, EventArgs e)
{
textBox1.Text += button4.Text;
lastCharIsSymbol = false;
}

private void button5_Click(object sender, EventArgs e)
{
textBox1.Text += button5.Text;
lastCharIsSymbol = false;
}

private void button6_Click(object sender, EventArgs e)
{
textBox1.Text += button6.Text;
lastCharIsSymbol = false;
}

private void button7_Click(object sender, EventArgs e)
{
textBox1.Text += button7.Text;
lastCharIsSymbol = false;
}

private void button8_Click(object sender, EventArgs e)
{
textBox1.Text += button8.Text;
lastCharIsSymbol = false;
}

private void button9_Click(object sender, EventArgs e)
{
textBox1.Text += button9.Text;
lastCharIsSymbol = false;
}

private void buttonAdd_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || lastCharIsSymbol)
return;
else
{
textBox1.Text += buttonAdd.Text;
currentString = textBox1.Text;
currentString = textBox1.Text.TrimEnd(mathSymbols);
//string[] numbers = currentString.Split(mathSymbols);
lastCharIsSymbol = true;
add = true;
}
}

private void buttonSubtract_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || lastCharIsSymbol)
return;
else
{
textBox1.Text += buttonSubtract.Text;
currentString = textBox1.Text;
currentString = textBox1.Text.TrimEnd(mathSymbols);
//string[] numbers = currentString.Split(mathSymbols);
lastCharIsSymbol = true;
subtract = true;
}
}

private void buttonMultiply_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || lastCharIsSymbol)
return;
else
{
textBox1.Text += buttonMultiply.Text;
currentString = textBox1.Text;
currentString = textBox1.Text.TrimEnd(mathSymbols);
//string[] numbers = currentString.Split(mathSymbols);
lastCharIsSymbol = true;
multiply = true;
}
}

private void buttonDivide_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || lastCharIsSymbol)
return;
else
{
textBox1.Text += buttonDivide.Text;
currentString = textBox1.Text;
currentString = textBox1.Text.TrimEnd(mathSymbols);
//string[] numbers = currentString.Split(mathSymbols);
lastCharIsSymbol = true;
divide = true;
}
}

private void buttonClear_Click(object sender, EventArgs e)
{
textBox1.Text = String.Empty;
}

private void buttonEquals_Click(object sender, EventArgs e)
{
if (add)
{

}

if (subtract)
{

}

if (multiply)
{

}

if (divide)
{

}
MessageBox.Show(currentString);
}
}
}[/source] Edited by Bill Fountaine

Share this post


Link to post
Share on other sites
Ah-ha, this is why I/we need to read the documentation. According to [url]http://msdn.microsoft.com/en-us/library/system.string.trimend.aspx[/url]:

[quote]The TrimEnd method removes from the current string all trailing characters that are in the trimChars parameter. The trim operation stops when the first character that is not in trimChars is encountered at the end of the string. For example, if the current string is "123abc456xyz789" and trimChars contains the digits from "1" through "9", the TrimEnd method returns "123abc456xyz".[/quote]

We want to take the string and remove all of the math operators from it, yes? So it seems that TrimEnd() doesn't quite do what we want - since it trims EVERYTHING from the end of the string up until it finds a character in the list of characters we gave it. Let's go see what else is [url=http://msdn.microsoft.com/en-us/library/7wtc81z6]available[/url].

It looks like there isn't any string method that removes all instances of a particular character. There is however, [url=http://msdn.microsoft.com/en-us/library/fk49wtc1]String.Replace[/url]. Now think: how can we "delete" the characters (or sub-strings) we don't want to see in our output string, given that we know this method exists? What kind of a "replace" operation is a "delete" operation analogous to?

Share this post


Link to post
Share on other sites
[quote name='Oberon_Command' timestamp='1341072630' post='4954330']
Ah-ha, this is why I/we need to read the documentation. According to [url="http://msdn.microsoft.com/en-us/library/system.string.trimend.aspx"]http://msdn.microsof...ng.trimend.aspx[/url]:

[quote]The TrimEnd method removes from the current string all trailing characters that are in the trimChars parameter. The trim operation stops when the first character that is not in trimChars is encountered at the end of the string. For example, if the current string is "123abc456xyz789" and trimChars contains the digits from "1" through "9", the TrimEnd method returns "123abc456xyz".[/quote]

We want to take the string and remove all of the math operators from it, yes? So it seems that TrimEnd() doesn't quite do what we want - since it trims EVERYTHING from the end of the string up until it finds a character in the list of characters we gave it. Let's go see what else is [url="http://msdn.microsoft.com/en-us/library/7wtc81z6"]available[/url].

It looks like there isn't any string method that removes all instances of a particular character. There is however, [url="http://msdn.microsoft.com/en-us/library/fk49wtc1"]String.Replace[/url]. Now think: how can we "delete" the characters (or sub-strings) we don't want to see in our output string, given that we know this method exists? What kind of a "replace" operation is a "delete" operation analogous to?
[/quote]

I originally thought of the Replace method, but instead of nothing, best you can do is use a whitespace character, which I figured would mess the program up somehow.

Edit: So I got rid of the + character, but now I have a pesky whitespace spot to deal with. Edited by Bill Fountaine

Share this post


Link to post
Share on other sites
[quote name='Bill Fountaine' timestamp='1341073622' post='4954333']
[quote name='Oberon_Command' timestamp='1341072630' post='4954330']
Ah-ha, this is why I/we need to read the documentation. According to [url="http://msdn.microsoft.com/en-us/library/system.string.trimend.aspx"]http://msdn.microsof...ng.trimend.aspx[/url]:

[quote]The TrimEnd method removes from the current string all trailing characters that are in the trimChars parameter. The trim operation stops when the first character that is not in trimChars is encountered at the end of the string. For example, if the current string is "123abc456xyz789" and trimChars contains the digits from "1" through "9", the TrimEnd method returns "123abc456xyz".[/quote]

We want to take the string and remove all of the math operators from it, yes? So it seems that TrimEnd() doesn't quite do what we want - since it trims EVERYTHING from the end of the string up until it finds a character in the list of characters we gave it. Let's go see what else is [url="http://msdn.microsoft.com/en-us/library/7wtc81z6"]available[/url].

It looks like there isn't any string method that removes all instances of a particular character. There is however, [url="http://msdn.microsoft.com/en-us/library/fk49wtc1"]String.Replace[/url]. Now think: how can we "delete" the characters (or sub-strings) we don't want to see in our output string, given that we know this method exists? What kind of a "replace" operation is a "delete" operation analogous to?
[/quote]

I originally thought of the Replace method, but instead of nothing, best you can do is use a whitespace character, which I figured would mess the program up somehow
[/quote]

Why can't you use an empty string? Or by "nothing" did you mean null? And how did you figure it would "mess the program up somehow?"

[source lang="csharp"]
currentString = textBox1.Text;

foreach (char symbol in mathSymbols)
currentString = currentString.Replace(symbol.ToString(), "");
[/source] Edited by Oberon_Command

Share this post


Link to post
Share on other sites
[quote name='Bill Fountaine' timestamp='1341073622' post='4954333']
[quote name='Oberon_Command' timestamp='1341072630' post='4954330']
Ah-ha, this is why I/we need to read the documentation. According to [url="http://msdn.microsoft.com/en-us/library/system.string.trimend.aspx"]http://msdn.microsof...ng.trimend.aspx[/url]:

[quote]The TrimEnd method removes from the current string all trailing characters that are in the trimChars parameter. The trim operation stops when the first character that is not in trimChars is encountered at the end of the string. For example, if the current string is "123abc456xyz789" and trimChars contains the digits from "1" through "9", the TrimEnd method returns "123abc456xyz".[/quote]

We want to take the string and remove all of the math operators from it, yes? So it seems that TrimEnd() doesn't quite do what we want - since it trims EVERYTHING from the end of the string up until it finds a character in the list of characters we gave it. Let's go see what else is [url="http://msdn.microsoft.com/en-us/library/7wtc81z6"]available[/url].

It looks like there isn't any string method that removes all instances of a particular character. There is however, [url="http://msdn.microsoft.com/en-us/library/fk49wtc1"]String.Replace[/url]. Now think: how can we "delete" the characters (or sub-strings) we don't want to see in our output string, given that we know this method exists? What kind of a "replace" operation is a "delete" operation analogous to?
[/quote]

I originally thought of the Replace method, but instead of nothing, best you can do is use a whitespace character, which I figured would mess the program up somehow.

Edit: Buuuuuut maybe, i've yet to try this out, after using Replace, using Trim to get rid of said whitespace.
[/quote]

you can replace with an empty string "" rather than a whitespace " ".

Edit, ninjad. need to learn to refresh before i reply ... Edited by SimonForsman

Share this post


Link to post
Share on other sites
[quote name='Oberon_Command' timestamp='1341073901' post='4954334']
[quote name='Bill Fountaine' timestamp='1341073622' post='4954333']
[quote name='Oberon_Command' timestamp='1341072630' post='4954330']
Ah-ha, this is why I/we need to read the documentation. According to [url="http://msdn.microsoft.com/en-us/library/system.string.trimend.aspx"]http://msdn.microsof...ng.trimend.aspx[/url]:

[quote]The TrimEnd method removes from the current string all trailing characters that are in the trimChars parameter. The trim operation stops when the first character that is not in trimChars is encountered at the end of the string. For example, if the current string is "123abc456xyz789" and trimChars contains the digits from "1" through "9", the TrimEnd method returns "123abc456xyz".[/quote]

We want to take the string and remove all of the math operators from it, yes? So it seems that TrimEnd() doesn't quite do what we want - since it trims EVERYTHING from the end of the string up until it finds a character in the list of characters we gave it. Let's go see what else is [url="http://msdn.microsoft.com/en-us/library/7wtc81z6"]available[/url].

It looks like there isn't any string method that removes all instances of a particular character. There is however, [url="http://msdn.microsoft.com/en-us/library/fk49wtc1"]String.Replace[/url]. Now think: how can we "delete" the characters (or sub-strings) we don't want to see in our output string, given that we know this method exists? What kind of a "replace" operation is a "delete" operation analogous to?
[/quote]

I originally thought of the Replace method, but instead of nothing, best you can do is use a whitespace character, which I figured would mess the program up somehow
[/quote]

Why can't you use an empty string? Or by "nothing" did you mean null? And how did you figure it would "mess the program up somehow?"

[source lang="csharp"]
currentString = textBox1.Text;

foreach (char symbol in mathSymbols)
currentString = currentString.Replace(symbol.ToString(), "");
[/source]
[/quote]

oh wow, i feel stupid.

When i was doing the replacing, I was replacing a char, not a string

and when replacing chars, you can't have an empty '', it has to be ' '.

It works with the string stuff, man I feel dumb >_>

Share this post


Link to post
Share on other sites
[quote name='Bill Fountaine' timestamp='1341074486' post='4954338']
Hm, even though i replaced with an empty string it still looks as if the number has a whitespace next to it.

Edit: Because when I do the debugging, it shows "56 " instead of "56"
[/quote]

if the string is entered as x + y rather than x+y then that is the expected result, it shouldn't matter though as the extra whitespace should be ignored when you convert from string to int anyway.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this