how to concatenate a - in a string c# [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
i am trying to make a calculator in c# and i am looking to concatenate a - into a string or something similar. the expected output should also minus the two variables. EX,
string ready;
private void minus_Click(object sender, EventArgs e)
{
long minusnumber = 32;
ready = minusnumber + "-";
}
.
.
.
private void equals_Click(object sender, EventArgs e)
{
long equalsNumber1 = 32;
ready += equalsNumber1;
MessageBox.Show(ready);
}
and console output would be 0
but it is taking "-" as minus not subtracting the two numbers.
ive tried escaping it (not sure if i did escape it right) and it didn't help:/

use
string.concat(minusnumber , "-");
It might help you. You can use n numbers of object on concat method.

I think this might be what you are hoping to accomplish, but it is a bit unclear. This will take minusnumber and negate it. So then when you add previous number to minusnumber, it will in effect subtract. Only problem with this is your ready variable appears to be a string.
private void minus_Click(object sender, EventArgs e)
{
long minusnumber = 32;
ready = -minusnumber;
}
Perhaps ready should be a long. When you are getting user input, you can use TryParse:
string userText = "54";
long userInput;
Int64.TryParse(userText, out userInput);
ready -= userInput;

From what you've written, the variable ready in minus_Click is local to minus_Click and not the global you probably intended it to be.
Instead of:
string ready = minusnumber + "-";
Perhaps you meant:
ready = minusnumber + "-";
EDIT
Now that the question is patched, it seems that the real question is "Why does MessageBox.Show(ready); show "32-32" instead of 0?" If that is the question, the reason is you are showing the value of the variable ready. This is a string. You started it at "32-" then added "32". The result of this string concatenation is "32-32". In order to perform arithmetic evaluation you need to write the code to parse the string and do the evaluation. Or find someone that has written an Eval() method for strings containing arithmetic expressions.

For make calculator you must use Polish Notation or RPN

Related

multiplication in C# basic program [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
In the Main function, declare three integer variables (name them arbitrarily) and initialize these variables with values (ideally different). Write a program that computes the following arithmetic expression: Multiply the values of the last two variables and subtract the value of the first variable from the obtained result. Write the arithmetic expression and its result on the screen in a suitable way.
using System;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
int prvni = 10;
int druha = 20;
int treti = 30;
int vysledek = (treti * druha) - prvni;
Console.WriteLine("Výsledek: {vysledek}");
}
}
}
String-interpolation in that way requires a $ (dollar-sign) before the string to specify that you are doing interpolation, so: Console.WriteLine($"Výsledek: {vysledek}");
For more examples on string interpolation: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
An alternative solution could be to simply concatenate the variable to the string: Console.WriteLine("Výsledek: " + vysledek);
You need to print the varable correctly.
Console.WriteLine("the answer {0}", vysledek);
Take care,
Ori

Initialize int variable to minus one in C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I've come across some code where the variables are initialized to minus one. That's in some old code, is there any reason behind that? Because as far as I know all value types are initialized to zero.
I've tested the code and it doesn't change anything to leave the int variable uninitialized or with minus one, the result is the same.
Would you enlighten me?
class Program
{
static void Main()
{
SampleDelegate del = new SampleDelegate(SampleMethodOne);
del += SampleMethodTwo;
int Number = -1; //or -> int Number;
int returnedValue = del(out Number);
Console.WriteLine("returnedValue = {0}", returnedValue);
Console.ReadLine();
}
public static int SampleMethodOne(out int Number)
{
return Number = 1;
}
public static int SampleMethodTwo(out int Number)
{
return Number = 3;
}
}
public delegate int SampleDelegate(out int Number);
/returns 2
TL;DR: it depends, maybe there is no answer
Possible answer:
Initializing variable is better. you never know how it can be used in some later functions where having an unexpected value may be dangerous (when the code is optimized, you cannot be sure of the default value if not initialized).
In some case, an int may be used for some compatibility reason in the API when you just need an uint. In such a case, initializing to a negative value may be an easy way to detect an unset/invalid value.
No real reason, just an habit from the developer. I agree with comments, ask him if possible

Modify the last letters of words? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I need to code a program, which changes the last two (or just the last) letter(s) of the inputted word because of some weird grammar rules of the Lithuanian language.
For example, my name is Kazys.
I want a code which could change the last two letters (ys) to another letter (y).
So when a person inputs
Kazys
The output would be
Hello, Kazy.
If a person inputs Balys, the code should change the name to Baly and print it.
I am just a beginner in C#. So, I don't even know some of the basic functions.
Any help is very appreciated!!
P.S. For those who wonder, why do I need this, I can tell you that it's a thing in Lithuanian grammar which requires to change the end of the word if you are addressing somebody.
I, personally, think language rules like this are why regular expressions exist. It allows you to easily make rules with look-aheads, look-behinds, etc., to make sure that the word is only changed if it fits a certain structure. For your example case, it should be as easy as:
var firstName = "Kazys";
var formattedFirstName = Regex.Replace(firstName, #"ys$", "y");
The $ at the end of the string means that it will only change "ys" to "y" when "ys" are the last two letters in a string.
Regular Expressions can get much more complicated and many people don't like them. However, I find them to be concise and clear most of the time.
You can write an extension class that applies the rules stored in a dictionary easy enough. Complicated rules could make Regex a better option, but if simple string replacement, a case insensitive dictionary could be better to avoid checking every possible rule every time.
public static class LanguageExtensions
{
// Define case insentive dictionary
public static Dictionary<string, string> Rules = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
// List rules here
{ "ys", "y"},
};
public static string ApplyRules(this string input)
{
string suffix;
if (input != null && input.Length > 2 && Rules.TryGetValue(input.Substring(input.Length - 2, 2), out suffix))
return input.Remove(input.Length - 2) + suffix;
else
return input;
}
}
Then, you just have to call the extension method:
Console.WriteLine("Kazys".ApplyRules()); // "Kazy"
Minimal working sample of what you might be after.
You seem to have complex requirements to code but, this is the basic concepts of replacing string(s) within a string.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace ChangeLastChar_46223845
{
public partial class Form1 : Form
{
TextBox txtbx_input = new TextBox();
TextBox txtbx_result = new TextBox();
Button btn = new Button();
public Form1()
{
InitializeComponent();
AddOurStuffToTheForm();
PutDefaultWordInInputBox();
}
private void PutDefaultWordInInputBox()
{
txtbx_input.Text = "Krazys";
}
private void AddOurStuffToTheForm()
{
txtbx_input.Location = new Point(5, 5);
btn.Location = new Point(5, txtbx_input.Location.Y + txtbx_input.Height + 5);
txtbx_result.Location = new Point(5, btn.Location.Y + btn.Height + 5);
btn.Text = "Substring";
btn.Click += Btn_Click;
this.Controls.Add(txtbx_input);
this.Controls.Add(btn);
this.Controls.Add(txtbx_result);
}
private void Btn_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtbx_input.Text) || string.IsNullOrWhiteSpace(txtbx_input.Text))
{
return;
}
if (txtbx_input.Text.EndsWith("ys"))
{
txtbx_result.Text = "Hello " + txtbx_input.Text.Substring(0, txtbx_input.Text.Length - 1);
}
}
}
}

Is there any benefit on declaring a local constant of string over a local variable C# [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Is there any noticeable benefit regarding performance on using a constant over a string. Suppose the following case
public void MethodUsingConstant()
{
const string searchedText = "foo";
//some operations using searchedText string
}
public void MethodNoUsingConstant()
{
string searchedText = "foo";
//some operations using searchedText string
}
There is also the option to take this to a class-struct constant field.
Or, should I avoid to overthink too much these micro optimizations?
If you think about it, it shouldn't really be much different. That is because when the computer sees a variable, it retrieves its memory adress and then the value. I have tried this code and the difference is so tiny (less than 3ms: BTW code ran in ~107 ms) that could be down to millions of other variables:
//Just changed to non const
const string s = "hello";
string full = "";
int k = 0;
for(int i = 0; i < 10000; i++)
{
full += s;
}
In general, const vs non const just comes down to this: will that value always stay the same: set it to const, else just leave it. Here is a great link about .NET optimization.
To sum up, You should only get into these tiny details the moment your code can't be optimized in any other way, and when that is the case, your code is just fine.

Good parsing approach after tokenization [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I wrote a program in which I read a string or file and tokenize it.
Example String :
"int w = sad&&s||a|d++ != == < > >= <= -- sadsa++ % int sads = 232.32; if reg string test = \"Hello World\";% % +- + - / * ** false true"
Exmaple Output:
Token[Type:'Identifier',Value:'int',Line:'1',Position:'3']
Token[Type:'Literal',Value:'w',Line:'1',Position:'4']
Token[Type:'Assign',Value:'=',Line:'1',Position:'4']
Token[Type:'Literal',Value:'sad',Line:'1',Position:'8']
Token[Type:'Logical',Value:'&&',Line:'1',Position:'8']
Token[Type:'Literal',Value:'s',Line:'1',Position:'11']
Token[Type:'Logical',Value:'||',Line:'1',Position:'11']
Token[Type:'Literal',Value:'a',Line:'1',Position:'14']
Token[Type:'Unknown',Value:'|d',Line:'1',Position:'14']
Token[Type:'Literal',Value:'d',Line:'1',Position:'16']
Token[Type:'Arithmetic',Value:'++',Line:'1',Position:'16']
Token[Type:'Relational',Value:'!=',Line:'1',Position:'18']
Token[Type:'Relational',Value:'==',Line:'1',Position:'20']
Token[Type:'Relational',Value:'<',Line:'1',Position:'22']
Token[Type:'Relational',Value:'>',Line:'1',Position:'23']
Token[Type:'Relational',Value:'>=',Line:'1',Position:'24']
Token[Type:'Relational',Value:'<=',Line:'1',Position:'26']
Token[Type:'Arithmetic',Value:'--',Line:'1',Position:'28']
Token[Type:'Literal',Value:'sadsa',Line:'1',Position:'35']
Token[Type:'Arithmetic',Value:'++',Line:'1',Position:'35']
Token[Type:'Arithmetic',Value:'%',Line:'1',Position:'37']
Token[Type:'Identifier',Value:'int',Line:'1',Position:'41']
Token[Type:'Literal',Value:'sads',Line:'1',Position:'45']
Token[Type:'Assign',Value:'=',Line:'1',Position:'45']
Token[Type:'DoubleValue',Value:'232.32',Line:'1',Position:'51']
Token[Type:'Semicolon',Value:';',Line:'1',Position:'51']
Token[Type:'Identifier',Value:'if',Line:'1',Position:'53']
Token[Type:'Literal',Value:'reg',Line:'1',Position:'56']
Token[Type:'Identifier',Value:'string',Line:'1',Position:'62']
Token[Type:'Literal',Value:'test',Line:'1',Position:'66']
Token[Type:'Assign',Value:'=',Line:'1',Position:'66']
Token[Type:'StringValue',Value:'Hello World',Line:'1',Position:'78']
Token[Type:'Semicolon',Value:';',Line:'1',Position:'78']
Token[Type:'Arithmetic',Value:'%',Line:'1',Position:'78']
Token[Type:'Arithmetic',Value:'%',Line:'1',Position:'79']
Token[Type:'Unknown',Value:'+-',Line:'1',Position:'80']
Token[Type:'Arithmetic',Value:'+',Line:'1',Position:'82']
Token[Type:'Arithmetic',Value:'-',Line:'1',Position:'83']
Token[Type:'Arithmetic',Value:'/',Line:'1',Position:'84']
Token[Type:'Arithmetic',Value:'*',Line:'1',Position:'85']
Token[Type:'Unknown',Value:'**',Line:'1',Position:'86']
Token[Type:'Identifier',Value:'false',Line:'1',Position:'93']
Token[Type:'Identifier',Value:'true',Line:'1',Position:'97']
Elapsed time: 31
(Ignore Position, has to be fixed in the future)
So now I do not really know a good approach to further interpret this in order to run a simple little scripting language on my own.
A good first approach is to come up with names for each thing, like "operation", "operand", "literal", "declaration" etc.
Then make a function that can read each of those from your token stream, and calls the others where appropriate. E.g. If you have:
operation: <operand> <operator> <operand>
operator: + | -
operand: <number> | <string>
etc., then you can have a function (pseudocode):
Operation parseOperation( tokens )
{
Operand operand1 = parseOperand( tokens )
Operation theOp = new Operation( tokens.fetchNextToken() )
Operand operand2 = parseOperand( tokens )
theOp.operand[0] = operand1
theOp.operand[1] = operand2
return theOp
}
and implement the other functions in a similar way. Of course, some functions may have to examine the next token to decide which other function to call, or even look ahead several tokens.
This is usually called a "recursive descent" parser.
Each of the functions returns an object that represents an operation and has its arguments hanging off of it. This is basically a tree structure, which you can then recursively walk ("depth-first").
The easiest way is to give the different object types you define dor your operations and values methods like asString() or asInt() and then do things like:
int Operation::asInt()
{
int a = operand[0].asInt()
int b = operand[1].asInt()
return a + b;
}
Objects that are already the right type (like an IntOperand class) would just return their value:
int IntOperand::asInt()
{
return self.numericValue
}
or whatever. Objects that aren't the right type either produce an error instead of returning a value, or convert themselves. So no matter how complex the expression, in the end you get an int or string or whatever out.
To run a program, you can now ask the bottom-most object for its value.

Categories