Can I put multiple statements in a interpolated string in C# 6? - c#

In Ruby, I can put multiple statements in a interpolated string, eg.
puts "#{a = 1; b = 2; a + b;}"
Or I can put them in multiple lines like this:
puts "#{a = 1;
b = 2;
a + b;}"
Can I do the same thing in C# 6? I've tried but failed. Below is my C# code.
Console.WriteLine($#"haha
{int a = 1;
int b = 2;
a+b;}
heihei");
When I try to run the C# program, I got:
CS1525 Invalid expression term 'int'
CS1073 Unexpected token 'a'
I hope someone can help.

You can't have full code blocks in your string interpolation statements. You can only do evaluations inside.
So this works (pulled the variables outside):
int a = 1;
int b = 2;
Console.WriteLine($#"haha
{a+b}
heihei");
And this too (do evaluation only):
Console.WriteLine($#"haha
{1+2}
heihei");

Ruby is different then C# in your case you write full code in your string interpolation so it's not working.
Console.WriteLine($"Name = {name}, hours = {hours:hh}")
or
Console.WriteLine($#"haha {1+2} heihei");
For Ref: Microsoft C#

Related

csharp string separetion for math operation

I'm doing a calculator with HTML CSS and JQuery with ajax call to a c# code (it's for an exercises given to me to learn a bit ajax and csharp).
I was able to do everything i needed to do, I'm just missing one thing.
The c# code, receive from a file named "Handler.ashx" a string, this string conteins the displalyed operation of the calculator, example: "321/34". now, I should, with c#, find a way to separate the 2 number inside the string and make the operation using the / used as separation. this for every single operation (+, -, /, *)
(I'm not english, so if somethings is not clear please tell me and I'll try to explaine myself better)
I'd use the built-in methods int IndexOf(char)
I am using C# 10 (or .Net 6.0), so depending on your version some features might not be available yet, but the logic should be the same
string test = "147+548";
int plusIndex = test.IndexOf('+');
int minusIndex = test.IndexOf('-');
int mulIndex = test.IndexOf('*');
int divIndex = test.IndexOf('/');
string operation;
float a = 0;
float b = 0;
if (plusIndex != -1)
{
operation = "PLUS";
a = float.Parse(test[..plusIndex]);
b = float.Parse(test[(plusIndex+1)..]);
}
else if (minusIndex != -1)
{
operation = "MINUS";
a = float.Parse(test[..minusIndex]);
b = float.Parse(test[(minusIndex + 1)..]);
}
else if (mulIndex != -1)
{
operation = "MULTIPLY";
a = float.Parse(test[..mulIndex]);
b = float.Parse(test[(mulIndex + 1)..]);
}
else/* if (divIndex == -1)*/
{
operation = "DIVIDE";
a = float.Parse(test[..divIndex]);
b = float.Parse(test[(divIndex + 1)..]);
}
Console.WriteLine($"{a} {operation} {b}");
The string[...] I put down are the same as SubString. [..5] means from start to index 5 and [6..] means from index 6 to the end

evaluate relational operator from a string

I have relational expressions stored in a database, that i have as strings in an iOS app. I would like to evaluate the conditions within the strings in C#, similar to the logic in the following psudo code:
string str1= "x > 0";
string str2= "y < 1";
int x = 1;
int y=0;
if(str1 && str2)
{
//do stuff
}
If the expressions are simple like the one in the example, then you can simply parse them. But if you have more complex expressions in mind, then I recommend taking a look at C# Expression Trees. The documentation does a good job of explaining it.
A much easier method would be to use library like: https://github.com/davideicardi/DynamicExpresso
Use Afk Expression Library (Afk link)
and try following code it will solve your problem as I sorted out.
Required NameSpace
using Afk.Expression;
Your code for sending expression as string to library evaluator
string str1 = "x > 0";
string str2 = "y < 1";
int x = 10;
int y = 0;
var st1=str1.Replace("x",x.ToString());
var st2 = str2.Replace("y", y.ToString());
if (Eval(st2) && Eval(st1))
{
//checked
}
Eval Method evaluate mathematical and conditional expression
bool Eval(string st)
{
ExpressionEval eval = new ExpressionEval(st);
return Convert.ToBoolean(eval.Evaluate().ToString());
}
As well read for more other libraries that you can utilize for your as such problems.

Convert string into mathematical expression [duplicate]

This question already has answers here:
Is there a string math evaluator in .NET?
(18 answers)
Closed 3 years ago.
Is there an easy way to parse a simple math expression represented as a string such as (x+(2*x)/(1-x)), provide a value for x, and get a result?
I looked at the VSAEngine per several online examples, however, I am getting a warning that this assembly has been deprecated and not to use it.
If it makes any differences, I am using .NET 4.0.
I urge caution against choosing an existing generic expression evaluator over a purpose-built math evaluator. The reason for this is expression evaluators are not limited to math. A clever individual could use this to create an instance of any type in the framework and call any method on the type, and that would allow him to do some decidedly unwelcome things. For example: new System.Net.WebClient().DownloadFile("illegalchildpornurl", "C:\openme.gif") will evaluate just fine in most of those, and do just what it sounds like it would (and make you a felon at the same time).
This doesn't mean don't look for something that's already written; it just means be careful. You want one that does math, and only math. Most of what's already out there isn't that picky.
I was recently using mXparser, which is a math parser library. It gives you a lot of flexibility, such as variables, functions, constants, operators. You will find below a few usage examples:
Example 1 - simple formula
Expression e = new Expression("1 + pi");
double v = e.calculate();
Example 2 - formula with variables, functions, etc.
Argument x = new Argument("x = 2");
Constant a = new Constant("a = sin(10)");
Function f = new Function("f(t) = t^2");
Expression e = new Expression("2*x + a - f(10)", x, a, f);
double v = e.calculate();
https://mxparser.codeplex.com/
https://mathparser.org/
Found recntly - you can try the syntax (and see the use case) via the Scalar Calculator app that is powered by mXparser.
Best regards
You can try using DataTable.Compute.
A related one is DataColumn.Expression.
Also check out: Doing math in vb.net like Eval in javascript
Note: I haven't used these myself.
I would also have a look at Jace (https://github.com/pieterderycke/Jace). Jace is a high performance math parser and calculation engine that supports all the .NET flavors (.NET 4.x, Windows Phone, Windows Store, ...). Jace is also available through NuGet: https://www.nuget.org/packages/Jace
Here is one way to do it. This code is written in Java. Note it does not handle negative numbers right now, but you can add that.
public class ExpressionParser {
public double eval(String exp, Map<String, Double> vars){
int bracketCounter = 0;
int operatorIndex = -1;
for(int i=0; i<exp.length(); i++){
char c = exp.charAt(i);
if(c == '(') bracketCounter++;
else if(c == ')') bracketCounter--;
else if((c == '+' || c == '-') && bracketCounter == 0){
operatorIndex = i;
break;
}
else if((c == '*' || c == '/') && bracketCounter == 0 && operatorIndex < 0){
operatorIndex = i;
}
}
if(operatorIndex < 0){
exp = exp.trim();
if(exp.charAt(0) == '(' && exp.charAt(exp.length()-1) == ')')
return eval(exp.substring(1, exp.length()-1), vars);
else if(vars.containsKey(exp))
return vars.get(exp);
else
return Double.parseDouble(exp);
}
else{
switch(exp.charAt(operatorIndex)){
case '+':
return eval(exp.substring(0, operatorIndex), vars) + eval(exp.substring(operatorIndex+1), vars);
case '-':
return eval(exp.substring(0, operatorIndex), vars) - eval(exp.substring(operatorIndex+1), vars);
case '*':
return eval(exp.substring(0, operatorIndex), vars) * eval(exp.substring(operatorIndex+1), vars);
case '/':
return eval(exp.substring(0, operatorIndex), vars) / eval(exp.substring(operatorIndex+1), vars);
}
}
return 0;
}
}
You need to import java.util.Map.
Here is how I use this code:
ExpressionParser p = new ExpressionParser();
Map vars = new HashMap<String, Double>();
vars.put("x", 2.50);
System.out.println(p.eval(" 5 + 6 * x - 1", vars));
Another option you may want to look into is the Spring.NET Framework's expression evaluation functionality. It can do a lot more than math, too.
However, the entire Spring.NET Framework might be a bit of overkill for your needs if you don't require the rest of the functionality.
Related: Equation expression parser with precedence.
As I answered in this thread (Best Free C# Math Parser using variables, user defined functions, custom operators), you can use Mathos Parser, which you can simply paste into your source code.
Mathos.Parser.MathParser parser = new Mathos.Parser.MathParser();
string expr = "(x+(2*x)/(1-x))"; // the expression
decimal result = 0; // the storage of the result
parser.LocalVariables.Add("x", 41); // 41 is the value of x
result = parser.Parse(expr); // parsing
Console.WriteLine(result); // 38.95
I recomend you to use MEEL for this.
// parse string to IExpression (symbolic type)
IExpression expression = BaseExpression.Parse("(x+(2*x)/(1-x))");
// create your own collection for attributes
var attributes = new MathAttributeCollection();
// create local variable named "x" with value 5
var attributeX = new ScalarAttrInt("x") {Value = new ScalarConstInt(5)};
attributes.Add(attributeX);
// execute math expression where x=5
var result = expression.Execute(attributes);
MessageBox.Show(result.GetText());
// result: 2.5

String(33, 0) in VB 6.0 and equivalent in C#

What is the meaning of UserName = String(33, 0) in VB 6.0 and what will be the equivalent in C#.
Please help I'm getting error while converting VB 6.0 code into C#.
Thanks in advance.
String in VB6 is a function that returns a string containing a repeating character string of the length specified.
String(number,character)
example:
strTest = String(5, "a")
' strTest = "aaaaa"
strTest = String(5, 97)
' strTest = "aaaaa" (97 is the ASCII code for "a")
In this case, String(33,0) will return a string containing 33 null characters.
The equivalent in C# would be
UserName = new String('\0', 33);
In VB6, that function creates a string that contains 33 characters, all of whom have zero ordinal value.
Typically you do that because you are about to pass the string to some native function which fills out the buffer. In C# the closest equivalent to that would be to create a StringBuilder instance which you would then pass to the native code in a p/invoke function call.
I think that a direct translation of that single line of code is not particularly useful. That code exists in context and I strongly suspect that the context is important.
So, whilst you could create a new C# string with 33 null characters, what would be the point of that? Since the .net string is immutable, you cannot do very much of interest with it. In your VB6 code you will surely be mutating that object, and so StringBuilder is, in my view, the most likely tool for the job.
I believe you are looking for:
UserName = new String((Char)0, 33);
Reference this for what the VB6 method did.
You can create an function that perform this action, or o can do a extenssion of the class String.
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(strGen("01",3));
}
//param s is the string that you can generete and the n param is the how many times.
private static string strGen(String s, int n){
string r = string.Empty;
for (int x = 1; x <= n; x++)
r += string.Copy(s);
return r;
}
}

Bitwise operations on strings - 1440 characters length

How can i make bitwise operations on strings at c#
example
string sr1="0101110";
string sr2="1101110";
sr1 & sr2="0101110";
or
sr1 | sr2="1101110";
How can i make such comparison ?
Notice string lengths are fixed 1440 characters
Here my dirty solution
private string compareBitWiseAnd(string sr1, string sr2)
{
char[] crArray1 = sr1.ToCharArray();
char[] crArray2 = sr2.ToCharArray();
StringBuilder srResult = new StringBuilder();
for (int i = 0; i < crArray1.Length; i++)
{
if (crArray1[i] == crArray2[i])
{
srResult.Append(crArray1[i]);
}
else
{
srResult.Append('0');
}
}
return srResult.ToString();
}
private string compareBitWiseOr(string sr1, string sr2)
{
char[] crArray1 = sr1.ToCharArray();
char[] crArray2 = sr2.ToCharArray();
StringBuilder srResult = new StringBuilder();
for (int i = 0; i < crArray1.Length; i++)
{
if (crArray1[i] == '1' || crArray2[i] == '1')
{
srResult.Append("1");
}
else
{
srResult.Append('0');
}
}
return srResult.ToString();
}
Convert to actual bits first, and then do the bitwise comparison.
int num1 = Convert.ToInt32(sr1, 2);
int num2 = Convert.ToInt32(sr2, 2);
int result = num1 & num2;
Use this if you want to get a binary string from the result.
BigInteger is the type you are looking for. It also have BitwiseOr.
If you really need to stick with strings it is not very hard to compute bitwise operations on character-by-character basis... but I'd avoid doing it if possible.
And here is a question on how to construct BigInteger from string of any base - BigInteger Parse Octal String?
var bitString = "10101";
BigInteger value = bitString.Aggregate(new BigInteger(), (b, c) => b * 2 + c - '0');
You have to convert the string to numbers first, you can use "Convert.ToInt32(String, Int32)", the second parameter lets you specify the base:
string sr1 = "0101110";
string sr2 = "1101110";
int one = Convert.ToInt32(sr1, 2);
int two = Convert.ToInt32(sr2, 2);
int result = one & two;
hope it helps.
You can't do bitwise operations on a string in the way you intend. There are interesting things you can do with bitwise operations on strings with other goals, like changing their case, but I think this is what you want:
// Convert the string to an integer
int foo = Convert.ToInt32(sr1, 2);
int bar = Convert.ToInt32(sr2, 2);
// Perform binary styff
int result = foo & bar;
// Convert back to a string, if you want
string resultStr = result.ToString();
I like Alexei's BigInteger solution, but it does require .NET 4.0 minimum. If for some reason you can't use that, then another option is to use the BitArray class, which has been available since .NET 1.1. Unfortunately, there is no method built-in to BitArray to parse a binary string, so you have to do that manually, similar to Alexei's solution.
Another option is a class I wrote called BoolArray which does a lot of the same things as BitArray, but does have a method to parse binary strings - use the static BoolArray.FromBinaryString method:
BoolArray bin = BoolArray.FromBinaryString("1001011000111010101"); // etc
Here is the BoolArray source code. Note, however, that it isn't quite complete, and isn't fully tested either, but I'm not immediately aware of any bugs.
EDIT: I noticed after pasting the original link that the code used a function provided in a different class of my "Utils" library, and wouldn't have compiled directly. I've updated the link to provide this class in the code as well... hopefully that was the only case, but if not let me know and I can fix.

Categories