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 8 years ago.
Improve this question
Hi fellow programmers,
I am creating a calculator in C#
and I have a string variable math which contains 100 * 5 - 2
How can I display its output which is 498 in my console?
My code is this:
String math = "100 * 5 - 2";
Console.WriteLine(math);
Console.ReadLine(); // For Pause
So basically, what my code will give me is the string itself which 100 * 5 - 2
but I want it to give me 498 as a result.
Idea about this is pretty much appreciated.
Thanks
Regular Expression evaluation can be done using DataTable.Compute method (from MSDN) :
Computes the given expression on the current rows that pass the filter
criteria.
Try this:
using System.Data;//import this namespace
string math = "100 * 5 - 2";
string value = new DataTable().Compute(math, null).ToString();
Simply try this
String math = (100 * 5 - 2).ToString();
I don't know, Why you want more complex? It's very easy ..
And if you want surely that,You can do that by using EvaluateExpression
public int EvaluateExpression(string math )
{
return Convert.ToInt32(math);
}
........................
String math = "100 * 5 - 2";
int result = EvaluateExpression(math );
Console.WriteLine(result );
See this discussions
Evaluating string "3*(4+2)" yield int 18
Update:
If those values came from input textbox, then write this way
String math = txtCalculator.Text.Trim();
int result = EvaluateExpression(math );
Console.WriteLine(result );
And also you can find out some pretty answer from this discussion
Is it possible to compile and execute new code at runtime in .NET?
Update 2:
Finally I have tried this sample for you :
My full code for class library
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.XPath;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
String math = "100 * 5 - 2";
Console.WriteLine(Evaluate(math));
}
public static double Evaluate(string expression)
{
var xsltExpression =
string.Format("number({0})",
new Regex(#"([\+\-\*])").Replace(expression, " ${1} ")
.Replace("/", " div ")
.Replace("%", " mod "));
// ReSharper disable PossibleNullReferenceException
return (double)new XPathDocument
(new StringReader("<r/>"))
.CreateNavigator()
.Evaluate(xsltExpression);
// ReSharper restore PossibleNullReferenceException
}
}
You can compile code from string at runtime and execute it:
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace DynamicCalcTest
{
class Program
{
static void Main(string[] args)
{
var result = new DynamicCalculator<double>("2 + 2 * 2").Execute();
}
}
public class DynamicCalculator<T>
{
private MethodInfo _Method = null;
public DynamicCalculator(string code)
{
_Method = GetMethodInfo(code);
}
public T Execute()
{
return (T)_Method.Invoke(null, null);
}
private MethodInfo GetMethodInfo(string code)
{
var tpl = #"
public static class Calculator
{{
public static double Calc()
{{
return {0};
}}
}}";
var finalCode = string.Format(tpl, code);
var parameters = new CompilerParameters();
parameters.ReferencedAssemblies.Add("mscorlib.dll");
parameters.GenerateInMemory = true;
parameters.CompilerOptions = "/platform:anycpu";
var options = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } };
var c = new CSharpCodeProvider(options);
var results = c.CompileAssemblyFromSource(parameters, finalCode);
var type = results.CompiledAssembly.GetExportedTypes()[0];
var mi = type.GetMethod("Calc");
return mi;
}
}
}
Related
I have this number in C#
Double a = 1.2345678
What I would like is for it to look like this after it's made into a string:
1.23456
First, convert it to string.
for example the string is defined as S.
then apply this method:
S.Remove(S.Length -2);
You can acheive that in many ways:
Code:
using System;
using System.Linq;
using System.Text;
namespace RemovingLastTwoNumber
{
class Program
{
static void Main(string[] args)
{
// Method 1.
double number = 1.2345678;
string numberInStringFormat = number.ToString();
string TargetNumber = numberInStringFormat.Substring(0, numberInStringFormat.Length - 2);
Console.WriteLine(number);
Console.WriteLine(TargetNumber);
// Method 2.
string _TargetNumber = Math.Round(number, 5).ToString();
Console.WriteLine(_TargetNumber);
// Method 3.
var characters = number.ToString().ToArray();
var __Characters = characters.Take(7);
StringBuilder __targetNumber = new StringBuilder();
foreach (var character in __Characters)
{
__targetNumber.Append(character);
}
Console.WriteLine(__targetNumber);
}
}
}
I need help linking or mapping a combo box to a parallel array in C#. I have a class project where I need to create a payroll system that displays the Net Pay after taxes.
I want to link parallel arrays that have all the employee information needed for payroll to the option selected in the combo box. I feel like I almost have it, but I don't know how to link the option selected from the combo box and the parallel arrays I have set up.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ZNSPayrollSystem
{
public partial class ZNSPayrollSystem : Form
{
public ZNSPayrollSystem()
{
InitializeComponent();
string[] arr = { "001 Peters", "002 Barnes", "003 Harris" };
cboEmp.DataSource = arr.ToArray();
}
private void btnCalc_Click(object sender, EventArgs e)
{
//parallel arrays
int[] empID = { 001, 002, 003 };
string[] empName = { "James Peters", "Sarah Barnes", "Candice Harris" };
double[] hrsWorked = { 40, 40, 40 };
double[] empWage = { 55.50, 65.50, 75.70 };
//declarations
double dblTaxRate = 8.2 / 100;
double dblNetPay;
double dblGrossPay;
double dblTaxWithheld;
dblGrossPay = hrsWorked[] * empWage[];
dblTaxWithheld = dblGrossPay * dblTaxRate;
dblNetPay = dblGrossPay - dblTaxWithheld;
txtGross.Text = dblGrossPay.ToString();
txtTax.Text = dblTaxWithheld.ToString();
txtNetPay.Text = dblNetPay.ToString();
}
}
}
Use the SelectedIndex property of the Combobox:
int i = cboEmp.SelectedIndex;
if (i != -1)
{
dblGrossPay = hrsWorked[i] * empWage[i];
}
i == -1 means nothing is selected. You may want to handle this separately to avoid getting any exceptions.
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 6 years ago.
Improve this question
By using RegEx, or String.Replace, I need to replace any number of consecutive #'s (with the appropriate number of leading 0's) with an integer. I know I can search for # in the string, get the First and Last index, Last-First for the length, then replace with String.Replace. I was hoping someone would have a faster, and more slick answer.
Method header would be:
string ReplaceHashtagsWithInt(string input, int integer)
Examples:
Input -> "String####_Hi##", 2
Output -> "String0002_Hi02"
Input -> "String####_Hi##", 123
Output -> "String0123_Hi123"
public static class Testing
{
public static void Main()
{
ReplaceHashtagsWithInt("String####_Hi##", 2);
ReplaceHashtagsWithInt("String####_Hi###", 123);
ReplaceHashtagsWithInt("String####_Hi#######", 123);
}
public static string ReplaceHashtagsWithInt(string input, int integer)
{
Regex regex = new Regex("#+");
var matches = regex.Matches(input).Cast<Match>().Select(m => m.Value).ToArray();
Array.Sort(matches);
Array.Reverse(matches);
foreach (string match in matches)
{
Regex r = new Regex(match);
string zeroes = new string('0', match.Length - integer.ToString().Length) + integer;
input = r.Replace(input, zeroes);
}
return input;
}
}
You can do something like this:
using System;
using System.Text;
using System.Text.RegularExpressions;
public static class Testing
{
public static void Main()
{
Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 1));
Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 23));
Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 456));
Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 7890));
Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 78901));
}
public static string ReplaceHashtagsWithInt(string input, int integer)
{
Regex regex = new Regex("#+");
StringBuilder output = new StringBuilder(input);
int allig = 0;
for(Match match = regex.Match(input);match.Success;match = match.NextMatch())
{
string num = integer.ToString();
if(num.Length<=match.Length)
for(int i=0;i<match.Length;i++)
{
if(i<match.Length-num.Length)
output[match.Index+i+allig] = '0';
else
output[match.Index+i+allig] = num[i-match.Length+num.Length];
}
else
{
output.Remove(match.Index+allig,match.Length);
output.Insert(match.Index+allig,num);
allig+=num.Length-match.Length;
}
}
return output.ToString();
}
}
if I have a string along the lines of: "user:jim;id:23;group:49st;"
how can I replace the group code (49st) with something else, so that it shows: "user:jim;id=23;group:76pm;"
sorry if the question is easy but I haven't found a specific answer, just cases different than mine.
You can use the index of "group" like this
string s = "user:jim;id:23;group:49st;";
string newS = s.Substring(0,s.IndexOf("group:") + 6);
string restOfS = s.IndexOf(";",s.IndexOf("group:") + 6) + 1 == s.Length
? ""
: s.Substring(s.IndexOf(";",s.IndexOf("group:") + 6) + 1);
newS += "76pm;";
s = newS + restOfS;
The line with the s = criteria ? true : false is essentially an if but it is put onto one line using a ternary operator.
Alternatively, if you know what text is there already and what it should be replaced with, you can just use a Replace
s = s.Replace("49st","76pm");
As an added precaution, if you are not always going to have this "group:" part in the string, to avoid errors put this inside an if which checks first
if(s.Contains("group:"))
{
//Code
}
Find the match using regex and replace it with new value in original string as mentioned below:
string str = "user:jim;id=23;group:49st;";
var match = Regex.Match(str, "group:.*;").ToString();
var newGroup = "group:76pm;";
str = str.Replace(match, newGroup);
This solution should work no matter where the group appears in the string:
string input = "user:jim;id:23;group:49st;";
string newGroup = "76pm";
string output = Regex.Replace(input, "(group:)([^;]*)", "${1}"+newGroup);
Here is a very generic method for splitting your input, changing items, then rejoining items to a string. It is not meant for single replacement in your example, but is meant to show how to split and join items in string.
I used Regex to split the items and then put results into a dictionary.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string pattern = "(?'name'[^:]):(?'value'.*)";
string input = "user:jim;id:23;group:49st";
Dictionary<string,string> dict = input.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => new
{
name = Regex.Match(x, pattern).Groups["name"].Value,
value = Regex.Match(x, pattern).Groups["value"].Value
}).GroupBy(x => x.name, y => y.value)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
dict["group"] = "76pm";
string output = string.Join(";",dict.AsEnumerable().Select(x => string.Join(":", new string[] {x.Key, x.Value})).ToArray());
}
}
}
That is just one way to do it. I hope it will help you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace stringi
{
class Program
{
static void Main(string[] args)
{
//this is your original string
string s = "user:jim;id:23;group:49st";
//string with replace characters
string s2 = "76pm";
//convert string to char array so you can rewrite character
char[] c = s.ToCharArray(0, s.Length);
//asign characters to right place
c[21] = s2[0];
c[22] = s2[1];
c[23] = s2[2];
c[24] = s2[3];
//this is your new string
string new_s = new string(c);
//output your new string
Console.WriteLine(new_s);
Console.ReadLine();
}
}
}
string a = "user:jim;id:23;group:49st";
string b = a.Replace("49st", "76pm");
Console.Write(b);
Hello I would like to convert this vba method into C#. I am trying to get the IDs of a selection and print them out. In particular I am having trouble converting the GetIDs() method(a built in method within visio vba) into C#.
Public Sub getCapabilityRectIDs()
Dim vsoSelection1 As Visio.Selection
Dim selectionIDs() As Long
Set vsoSelection1 = Application.ActiveWindow.Page.CreateSelection(visSelTypeByLayer, visSelModeSkipSuper, "Capability")
Application.ActiveWindow.Selection = vsoSelection1
Call vsoSelection1.GetIDs(selectionIDs)
For i = 0 To UBound(selectionIDs)
Debug.Print selectionIDs(i)
Next i
End Sub
This is what I have so far in C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Visio = Microsoft.Office.Interop.Visio;
class Program
{
static void Main(string[] args)
{
//create the object that will do the drawing
VisioDrawer Drawer = new VisioDrawer();
Drawer.selectShpLayer("Capability");
}
}
class VisioDrawer
{
public Visio.Application VisApp;
public static Visio.Page acPage;
public Visio.Selection LayerSelection;
public VisioDrawer()
{
//create the application
VisApp = new Visio.Application();
VisApp.Documents.Open(#"............. - abc.vsdm");
ActiveDoc = VisApp.ActiveDocument;
acPage = VisApp.ActivePage;
}
public void selectShpLayer (string layerName){
Int i = 0;
long[] lngRowIDs;
//this selects the shapes of the selected layer
LayerSelection = acPage.CreateSelection(Microsoft.Office.Interop.Visio.VisSelectionTypes.visSelTypeByLayer, Microsoft.Office.Interop.Visio.VisSelectMode.visSelModeOnlySuper,layerName);
LayerSelection.GetIDs(lngRowIDs);
for (i = 0; i < lngRowIDs.Length; i++)
{
Debug.Write(lngRowIDs[i]);
}
}
}
Thanks in advance!
I created a visio doc and drew 3 simple shapes. I then created a layer called "cool" and added those 3 shapes to it.
I don't understand enough about the shape selection, you had visSelModeOnlySuper which may work for you, but did not work for the case I created. The default is visSelModeSkipSuper (which worked for me)
Here's the API page that describes how to use the createSelection:
https://msdn.microsoft.com/en-us/library/office/ff765565.aspx
Here is my sample code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Visio = Microsoft.Office.Interop.Visio;
class Program
{
static void Main(string[] args)
{
//create the object that will do the drawing
VisioDrawer Drawer = new VisioDrawer();
Drawer.selectShpLayer("cool");
}
}
class VisioDrawer
{
public Visio.Application VisApp;
public static Visio.Page acPage;
public Visio.Selection LayerSelection;
public VisioDrawer()
{
//create the application
VisApp = new Visio.Application();
VisApp.Documents.Open(#"c:\temp\trial.vsdm");
acPage = VisApp.ActivePage;
}
public void selectShpLayer(string layerName)
{
int i = 0;
int[] lngRowIDs;
Array lngRowIDArray;
//this selects the shapes of the selected layer
LayerSelection = acPage.CreateSelection(Microsoft.Office.Interop.Visio.VisSelectionTypes.visSelTypeByLayer, Microsoft.Office.Interop.Visio.VisSelectMode.visSelModeSkipSuper, layerName);
LayerSelection.GetIDs(out lngRowIDArray);
lngRowIDs = (int[])lngRowIDArray;
for (i = 0; i < lngRowIDs.Length; i++)
{
Debug.Write("Object ID: " + lngRowIDs[i].ToString() + "\n");
}
}
}
And it produces this output:
Object ID: 1
Object ID: 2
Object ID: 3
If you change the debug line to this:
Debug.Write("Object ID: " + lngRowIDs[i].ToString() + " -- " + acPage.Shapes.ItemFromID[i].Name + "\n");
The output gets even more useful:
Object ID: 1 -- ThePage
Object ID: 2 -- Circle
Object ID: 3 -- Rectangle