How could I create a string with an object value in it? - c#

This questions really isn't hard to understand. I have always wondered this and wondered if possible, how could it be done. Well this is sort what I'd like to do if possible:
int number = 50;
string text = "The number is %number";
Where I wrote %number in the string above, I would like the value of number to be inserted into the string, because the way I would usually go about doing something like this would be like:
int number = 50;
string text = "The number is " + number.ToString();
Which yes, the way I integrated number into the string above is an okay way of doing so, but I have always wondered, is it possible to do something such as the first example I wrote, where to put a value of an object into a string all you would have to do is write some type of character or string (used to reference the object), along with the name of the object into a string to get a result of a string with the value of the object in it? Or is there anything sort of like this you're able to do?

You would use string.Format:
string text = string.Format("The number is {0}", number);
Note that all objects have a ToString method, which means that all objects can be used as arguments to string.Format, however the default response from ToString is to return the full name of the type, which might not make much sense.
For instance, this:
public class Dummy
{
}
var d = new Dummy();
string text = string.Format("The dummy is {0}", d);
will assign something like the following value to text:
"The dummy is Your.Namespace.Dummy";
You have two options:
Override ToString and return something meaningful for your new type
Read off a property or something instead, e.g.:
string text = string.Format("The dummy is {0}", d.SomeProperty);
Also note that string.Format can take multiple arguments:
int a = 10;
int b = 20;
int c = a + b;
string text = string.Format("{0} + {1} = {2}", a, b, c);
There's a lot more to string.Format than what I have shown here, so click the link to the documentation (first line of this answer) to learn more.

You probably need to check Sting.Format
string text = String.Format("The number1 is {0},number2 is {1}", number1, number2);
It is also worth to check this discussion regarding When is it better to use String.Format vs string concatenation?
`

Related

formatting decimals using string format

public static string PadZero(this double number, int decimalPlaces)
{
var requiredFormat = "0." + "".PadRight(decimalPlaces, '0');
var something = $"{number:requiredFormat}";
return number.IsNotZero() ? something: string.Empty;
}
This is a helper function to pad zeros to a double number, user can pass the number of zeros that is required to be padded through decimalPlaces.
Above function fails my unit tests, output received is {requiredFormat} in all test cases.
I have just replaced: var something = $"{number:0.00}"; with a generic variable requiredFormat that can handle any number of zero padding.
There are two problems with your example. The first is that the value of something is not going to produce a string that can be used to format a number. The second is that you are not using something to perform a number format by using string.format.
So first off, the statement:
var something = $"{number:requiredFormat}";
is not going to give you the result that you want, which would be a string that looks something like:
{0:0.0000}
Try changing the code to read:
var something = $"{{0:{requiredFormat}}}";
If you do Console.WriteLine(something) after that statement executes you can inspect the value of something to make sure it is what you are looking for.
After that, change this line:
return number.IsNotZero() ? something: string.Empty;
to read:
return number.IsNotZero() ? string.Format(something, number) : string.Empty;
Even with Interpolated Strings, you have to build the variable format and apply it in two separate steps.
Hope that helps.

Insert spaces into string using string.format

I've been using C# String.Format for formatting numbers before like this (in this example I simply want to insert a space):
String.Format("{0:### ###}", 123456);
output:
"123 456"
In this particular case, the number is a string. My first thought was to simply parse it to a number, but it makes no sense in the context, and there must be a prettier way.
Following does not work, as ## looks for numbers
String.Format("{0:### ###}", "123456");
output:
"123456"
What is the string equivalent to # when formatting? The awesomeness of String.Format is still fairly new to me.
You have to parse the string to a number first.
int number = int.Parse("123456");
String.Format("{0:### ###}", number);
of course you could also use string methods but that's not as reliable and less safe:
string strNumber = "123456";
String.Format("{0} {1}", strNumber.Remove(3), strNumber.Substring(3));
As Heinzi pointed out, you can not have format specifier for string arguments.
So, instead of String.Format, you may use following:
string myNum="123456";
myNum=myNum.Insert(3," ");
Not very beautiful, and the extra work might outweigh the gains, but if the input is a string on that format, you could do:
var str = "123456";
var result = String.Format("{0} {1}", str.Substring(0,3), str.Substring(3));
string is not a IFormattable
Console.WriteLine("123456" is IFormattable); // False
Console.WriteLine(21321 is IFormattable); // True
No point to supply a format if the argument is not IFormattable only way is to convert your string to int or long
We're doing string manipulation, so we could always use a regex.
Adapted slightly from here:
class MyClass
{
static void Main(string[] args)
{
string sInput, sRegex;
// The string to search.
sInput = "123456789";
// The regular expression.
sRegex = "[0-9][0-9][0-9]";
Regex r = new Regex(sRegex);
MyClass c = new MyClass();
// Assign the replace method to the MatchEvaluator delegate.
MatchEvaluator myEvaluator = new MatchEvaluator(c.ReplaceNums);
// Replace matched characters using the delegate method.
sInput = r.Replace(sInput, myEvaluator);
// Write out the modified string.
Console.WriteLine(sInput);
}
public string ReplaceNums(Match m)
// Replace each Regex match with match + " "
{
return m.ToString()+" ";
}
}
How's that?
It's been ages since I used C# and I can't test, but this may work as a one-liner which may be "neater" if you only need it once:
sInput = Regex("[0-9][0-9][0-9]").Replace(sInput,MatchEvaluator(Match m => m.ToString()+" "));
There is no way to do what you want unless you parse the string first.
Based on your comments, you only really need a simple formatting so you are better off just implementing a small helper method and thats it. (IMHO it's not really a good idea to parse the string if it isn't logically a number; you can't really be sure that in the future the input string might not be a number at all.
I'd go for something similar to:
public static string Group(this string s, int groupSize = 3, char groupSeparator = ' ')
{
var formattedIdentifierBuilder = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
if (i != 0 && (s.Length - i) % groupSize == 0)
{
formattedIdentifierBuilder.Append(groupSeparator);
}
formattedIdentifierBuilder.Append(s[i]);
}
return formattedIdentifierBuilder.ToString();
}
EDIT: Generalized to generic grouping size and group separator.
The problem is that # is a Digit placeholder and it is specific to numeric formatting only. Hence, you can't use this on strings.
Either parse the string to a numeric, so the formatting rules apply, or use other methods to split the string in two.
string.Format("{0:### ###}", int.Parse("123456"));

Default number format for ToString

Is it possible to define a default number format that is used whenever I convert an integer (or double etc.) to a String without specifying a format string?
C# example:
int i = 123456;
string s = "Hello " + i;
// or alternatively with string.Format without format definition
string s = string.Format("Hello {0}", i);
ASP.NET Razor example:
<div>
Hello #i
</div>
I think all these code lines implicitly use the default ToString() method for Int32. And not surprisingly, all these code lines result in "Hello 123456", but I want "Hello 123,456".
So can I specify that "N0" should be used by default (at least for integer)?
I already found the question Set Default DateTime Format c# - it looked good, but it doesn't help me for numbers.
Edit: I'm aware that I could write an extension method which I can use throughout my application, but this is not what I'm looking for. I would like to find a property (maybe somewhere hidden in CultureInfo or NumberFormatInfo) which is currently set to "G" and is used by the default Int32.ToString() implementation.
If you create your own CultureInfo and you can alter it and then assign it to CultureInfo.CurrentCulture like in this answer:
https://stackoverflow.com/a/24785761/166921
You Can override systems toString() method into your class as under:
public override string ToString()
{
int i = 123456;
string s = "Hello " + i;
return string.Format("Hello {0}", i);
}
you can use extension methods
public static class MyExtensions
{
public static string ToDefaultFormatString(this int i)
{
//Staf
}
}
and your code look like
int i = 123456;
string s = "Hello " + i.ToDefaultFormatString();
As you are trying to modify the functionality for a primitive type, which has no class, you cannot override the ToString() method.
You can however create an extension method.
namespace System
{
public class IntExt
{
public string ToStringN0(this int i)
{
return i.ToString("N0");
}
}
}
and then use by
int i = 5000;
Console.WriteLine(i.ToStringN0());
The example puts the class in the System namespace so it will be available through the application.
This maybe help you :
Decimal.ToString Method (String) MSDN
Double.ToString Method (String) MSDN
asp.net mvc set number format default decimal thousands separators

Adding a text stored in a variable to string to be saved to a text file

Hi I am trying to save text to a text file with some string, e.g. the students name added to it, but I'm a bit stuck
string iName2 = iName;
string text = "The student named {0} needs more work with plurals";
System.IO.File.WriteAllText(#"C:\Users\user\documents\visual studio 2012\Projects\Artificial_Intelligence_Project_3\WindowsFormsApplication1\Info.txt", text);`
I'm assuming iName is the name. String.Format is the method you need:
string text = String.Format("The student named {0} needs more work with plurals", iName);
Unless you need iName2 somewhere else, you do not need it.
Apart from being more readable, String.Format has one advantage over string concatenation with +. It allows you to change the order of substituted text fragments or omit some of them:
string text = String.Format("{0} {1}", a, b);
// changed order within text without changing argument order!
string text2 = String.Format("{1} {0}", a, b);
This is particularly useful if you're doing localization: Different languages have different rules to construct phrases, where the fragments may need to be substituted in different order.
string text = "The student named " + iName2 + " needs more work with plurals";

How to get rid of conversion overheads?

Take this example:
customer.Salary = Convert.ToDecimal(string.Format("{0}! ", Console.ReadLine().ToString()));
(1) Why in C# we need to always put .ToString() to get it right?
(2) Convert.To... Doesn't it creates overheads unnecessarily?
Further in the below given code: It gives error: "Input string was not in a correct format", after accepting user input.
// Main begins program execution.
public static void Main()
{
Customer customer = new Customer();
// Write to console/get input
Console.Write("Enter customer's salary: ");
customer.Salary = Convert.ToDecimal(string.Format("{0}! ", Console.ReadLine().ToString()));
Console.WriteLine("Salary in class variable is: {0}", customer.Salary.ToString());
Console.Read();
}
class Customer
{
public Decimal Salary { get; set; }
}
Here again, either I must use:
string sal = Convert.ToDecimal(string.Format("{0}! ", Console.ReadLine().ToString()));
customer.Salary = Convert.ToDecimal(sal);
Or, I must change the data type itself in the Customer class.
Can this overhead be avoided with anything in Generics?
You do not need to call .ToString().
Yes, it does.
You're trying to write
customer.Salary = Decimal.Parse(Console.ReadLine());
Your current code does the following:
Console.ReadLine(): Reads a line from the console, returning a String object.
(...).ToString() Returns the same String object
string.Format("{0}! ", (...)): Returns a new String object containing the original string followed by !.
Convert.ToDecimal((...)): Tries to parse that into a Decimal value.
Since the string ends with !, it fails
I think you'll be happier if you use Decimal.Parse or Decimal.TryParse to do the conversions, rather than relying on Convert.ToDecimal. You can write:
Decimal tempSal;
string sal = Console.ReadLine();
if (Decimal.TryParse(sal, out tempSal))
{
customer.Salary = tempSal;
}
else
{
// user entered bad data
}

Categories

Resources