This question already has answers here:
String Interpolation vs String.Format
(7 answers)
Closed 5 years ago.
I'm a beginner to C#. So far I came across several ways that I can use to embed variables in a string value. One of the is String Interpolation which was introduced in C# 6.0. Following code is an example for String Interpolation.
int number = 5;
string myString = $"The number is {number}";
What I want to know is whether there is a benefit of using String Interpolation over the following ways to format a string.
// first way
int number = 5;
string myString = "The number is " + number;
//second way
int number = 5;
string myString = string.Format("The number is {0}", number);
The first way that you have shown will create multiple strings in memory. From memory I think it creates the number.ToString() string, the literal "The number is " string and then the string with name myString
For the second way that you show it's very simple: String interpolation compiles to the string.Format() method call that you use.
EDIT: The second way and the interpolation will also support format specifiers.
A more detailed discussion by Jon Skeet can be found here: http://freecontent.manning.com/interpolated-string-literals-in-c/
Related
This question already has answers here:
How can I parse the int from a String in C#?
(4 answers)
Closed 3 months ago.
I have this line of code
bool containsInt = "Sanjay 400".Any(char.IsDigit)
What I am trying to do is extract the 400 from the string but
Any(char.IsDigit)
only returns a true value. I am very new to coding and c# especially.
As you already found out, you cannot use Any for extraction.
You would need to use the Where method:
List<char> allInts = "Sanjay 400".Where(char.IsDigit).ToList();
The result will be a list containing all integers/digits from your string.
Ok if you are interested in the value as integer you would need to convert it again to a string and then into an integer. Fortunately string has a nice constructor for this.
char[] allIntCharsArray = "Sanjay 400".Where(char.IsDigit).ToArray();
int theValue = Convert.ToInt32(new string(allIntCharsArray));
If you are using .NET 5 or higher you could also use the new cool TryParse method without extra string conversion:
int.TryParse(allIntCharsArray, out int theValue);
int result = int.Parse(string.Concat("Sanjay 400".Where(char.IsDigit)));
Use the Regex
var containsInt = Convert.ToInt32(Regex.Replace(#"Sanjay 400", #"\D", ""));
Regular expressions allow you to take only numbers and convert them into integers.
This question already has answers here:
Is there a string math evaluator in .NET?
(18 answers)
Closed 1 year ago.
how can I convert a string to be an equation with variable avoiding function eval()?
I'm working on .net core and I have this
decimal total;
string var;
total = total + var;
but the string var is an equation with variable for now can be "1" or "total*2/100" but in future can be something else
You can't assign the result of equation to total because the equation may result into a decimal number and total is of type int.
using System.Data;
double result = Double.Parse(new DataTable().Compute($"{total}+{var.Replace("total", total+"")}", "")+"");
the concatenations with an empty string is to convert the object returned by Compute() method to string and int type (total) to string because the Double.Parse() method and Replace() methods expect a string in their parameters.
This question already has answers here:
Add zero-padding to a string
(6 answers)
Closed 4 years ago.
I have a very simple Question to ask.
I have a string like:
string str="89";
I want to format my string as follow :
str="000089";
How can i achieve this?
Assuming the 89 is actually coming from another variable, then simply:
int i = 89;
var str = i.ToString("000000");
Here the 0 in the ToString() is a "zero placeholder" as a custom format specifier; see https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings
If you have a string (not int) as the initial value and thus you want to pad it up to length 6, try PadLeft:
string str = "89";
str = str.PadLeft(6, '0');
If you want the input to be a string you'll have to parse it before you output it
int.Parse(str).ToString("000000")
This question already has answers here:
.NET String.Format() to add commas in thousands place for a number
(23 answers)
Closed 9 years ago.
I'm trying to put comma's between long numbers automatically, but so far without success. I'm probably making a very simple mistake, but so far I can't figure it out. This is the code I currently have, but for some reason I'm getting 123456789 as the output.
string s = "123456789";
string.Format("{0:#,###0}", s);
MessageBox.Show(s); // Needs to output 123,456,789
var input = 123456789;
// these two lines amount to the same thing
Console.WriteLine(input.ToString("N0"));
Console.WriteLine(string.Format("{0:N0}", input));
If, as per your question, you need to start with a string:
var stringInput = "123456789";
var input = int.Parse(stringInput);
// these two lines amount to the same thing
Console.WriteLine(input.ToString("N0"));
Console.WriteLine(string.Format("{0:N0}", input));
You'll possibly also need to take culture into account when parsing/formatting. See the overloads that take an IFormatProvider.
Try this:
string value = string.Format("{0:#,###0}", 123456789);
In your code you are missing the initial { in the format string, and then number formatting options apply to numbers, while your s is a string.
You could convert the string to a number with int.Parse:
int s = int.Parse("123456789");
string value = string.Format("{0:#,###0}", 123456789);
MessageBox.Show(value);
This should work (you need to pass String.Format() a number, not another String):
Int32 i = 123456789;
String s = String.Format("{0:#,###0}", i);
MessageBox.Show(s);
But consider the format string you're using...there are cleaner options available, as others are suggesting.
Look at the number formatting information on MSDN: Standard Numeric Format Strings, or optionally at the custom format strings: Custom Numeric Format Strings.
For custom number formats:
The "," character serves as both a group separator and a number scaling specifier.
double value = 1234567890;
Console.WriteLine(value.ToString("#,#", CultureInfo.InvariantCulture));
// Displays 1,234,567,890
Console.WriteLine(value.ToString("#,##0,,", CultureInfo.InvariantCulture));
// Displays 1,235
There is so much wrong with your code, that's it's hard to describe every detail.
Look at this example:
namespace ConsoleApplication1
{
using System;
public class Program
{
public static void Main()
{
const int Number = 123456789;
var formatted = string.Format("{0:#,###0}", Number);
Console.WriteLine(formatted);
Console.ReadLine();
}
}
}
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Convert.ToInt32() a string with Commas
i have a value in the label as: 12,000
and i wish to convert it into an integer like 12000 (use it for comparison)
i tried int k = convert.toint32("12,000"); this does not work.
Thanks
You're being screwed up by the comma. If all of your values have commas in them, you'll want to run a string.replace() to remove them. Once that comma is gone, it should work fine.
A more thorough way would be to Parse it, allowing for thousands.
Try the following
var number = Int32.Parse("12,000", System.Globalization.NumberStyles.AllowThousands);
Try this
string num = "12,000";
int k = Convert.ToInt32(num.Replace(",",""));
string k = "12,000";
int i = Convert.ToInt32(k.Replace(",", ""));
will work