String Formatting
Part of the Fundamentals section of Coddy's C# journey — lesson 63 of 69.
In C#, String.Format() is a powerful method used to create formatted strings. It allows you to combine text with variables in a readable and customizable way. This method uses format specifiers to define how variables should be inserted into the string.
Let's learn how to use string formatting in C#:
The basic syntax of String.Format() is:
string formattedString = String.Format("format_string", arg0, arg1, ...);Where:
format_string: A string that contains text and format specifiers.arg0, arg1, ...: The variables to be inserted into theformat_string.
Let's look at the format specifiers. The numbers in the curly braces refer to the position of the arguments:
{0}: Refers to the first argument (arg0){1}: Refers to the second argument (arg1){2}: Refers to the third argument (arg2)- And so on...
Let's try a simple example with different types of arguments:
string name = "Alice";
int age = 30;
double price = 19.99;
string formatted = String.Format("Name: {0}, Age: {1}, Price: {2}", name, age, price);
Console.WriteLine(formatted);After executing this code, you will see on the screen: Name: Alice, Age: 30, Price: 19.99
You can also control the formatting further with format specifiers after a colon. The format specifier consists of a letter (like F for fixed-point decimal) followed by an optional number for precision:
// Format a number with 2 decimal places
double number = 123.4567;
string formatted = String.Format("The value is {0:F2}", number);
Console.WriteLine(formatted);After executing this code, you will see on the screen: The value is 123.46
You can use F1, F2, F3, etc. to specify different numbers of decimal places
Challenge
EasyCreate a method named CreateFormattedString that takes the following arguments:
- A string
productName. - An integer
quantity. - A double
unitPrice.
The method should return a formatted string that combines these values in the following format:
Product: [productName], Quantity: [quantity], Unit Price: [unitPrice]Format the unitPrice to five decimal places, the quantity with one decimal place (convert it to double), and the first char of productName should be uppercase.
For example, if productName is "laptop", quantity is 3, and unitPrice is 1299.9999, the method should return:
Product: Laptop, Quantity: 3.0, Unit Price: 1299.99990To extract the first char while maintaining it in String type rather then char type use:
str.Substring(0,1)
Cheat sheet
The String.Format() method creates formatted strings by combining text with variables using format specifiers.
Basic syntax:
string formattedString = String.Format("format_string", arg0, arg1, ...);Format specifiers use curly braces with position numbers:
{0}: First argument{1}: Second argument{2}: Third argument
Example with multiple data types:
string name = "Alice";
int age = 30;
double price = 19.99;
string formatted = String.Format("Name: {0}, Age: {1}, Price: {2}", name, age, price);
Console.WriteLine(formatted); // Output: Name: Alice, Age: 30, Price: 19.99Format specifiers with precision control using colon:
double number = 123.4567;
string formatted = String.Format("The value is {0:F2}", number);
Console.WriteLine(formatted); // Output: The value is 123.46You can use F1, F2, F3, etc. to specify different numbers of decimal places
To extract the first character as a string: str.Substring(0,1)
Try it yourself
using System;
public class Program {
public static string CreateFormattedString(string productName, int quantity, double unitPrice) {
// Write your code here
}
public static void Main(string[] args) {
string product = Console.ReadLine();
int qty = int.Parse(Console.ReadLine());
double price = double.Parse(Console.ReadLine());
string formattedString = CreateFormattedString(product, qty, price);
Console.WriteLine(formattedString);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic Shortcuts5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3