Showing posts with label Format Strings. Show all posts
Showing posts with label Format Strings. Show all posts

Aug 11, 2011

C# Replace String Examples


You want to replace one substring in a string with another in your C# program. You may need to swap specific characters with other characters or words. Also, see if you can optimize string replacements with StringBuilder. This page has some Replace method examples, and also a real-world example of using StringBuilder Replace, using the C# programming language.
Key points:Replace is an instance method on String. It replaces all instances of the specified string. It returns a copied string. The original string is not changed.

Example 1

Here we see a very simple example of using the string Replace method. Note that you must assign the result of the string Replace method to a new variable. Other Replace methods in the base class library may not require this.

Program that uses Replace [C#]

using System;

class Program
{
    static void Main()
    {
	const string s = "vamsi is scary.";
	Console.WriteLine(s);

	// Note:
	// You must assign the result of Replace to a new string.
	string v = s.Replace("scary", "not scary");
	Console.WriteLine(v);
    }
}

Output

 vamsi is scary.
 vamsi is not scary.

Aug 5, 2011

Replace Line Breaks in a String C#

Use replace with environment.newline





myString = myString.Replace(Environment.NewLine, "replacement text")


   string line = ...

line = line.Replace( "\r", "").Replace( "\n", "" );


Jul 12, 2011

String Format for Double [C#]



String Format for Double [C#]

The following examples show how to format float numbers to string in C#. You can use static method String.Format or instance methods double.ToString and float.ToString.

Digits after decimal point

This example formats double to string with fixed number of decimal places. For two decimal places use pattern „0.00“. If a float number has less decimal places, the rest digits on the right will be zeroes. If it has more decimal places, the number will be rounded.
[C#]
// just two decimal places
String.Format("{0:0.00}", 123.4567);      // "123.46"
String.Format("{0:0.00}", 123.4);         // "123.40"
String.Format("{0:0.00}", 123.0);         // "123.00"

Next example formats double to string with floating number of decimal places. E.g. for maximal two decimal places use pattern „0.##“.
[C#]
// max. two decimal places
String.Format("{0:0.##}", 123.4567);      // "123.46"
String.Format("{0:0.##}", 123.4);         // "123.4"
String.Format("{0:0.##}", 123.0);         // "123"

Digits before decimal point

If you want a float number to have any minimal number of digits before decimal point use N-times zero before decimal point. E.g. pattern „00.0“ formats a float number to string with at least two digits before decimal point and one digit after that.
[C#]
// at least two digits before decimal point
String.Format("{0:00.0}", 123.4567);      // "123.5"
String.Format("{0:00.0}", 23.4567);       // "23.5"
String.Format("{0:00.0}", 3.4567);        // "03.5"
String.Format("{0:00.0}", -3.4567);       // "-03.5"

Thousands separator

To format double to string with use of thousands separator use zero and comma separator before an usual float formatting pattern, e.g. pattern „0,0.0“ formats the number to use thousands separators and to have one decimal place.
[C#]
String.Format("{0:0,0.0}", 12345.67);     // "12,345.7"
String.Format("{0:0,0}", 12345.67);       // "12,346"

Zero

Float numbers between zero and one can be formatted in two ways, with or without leading zero before decimal point. To format number without a leading zero use # before point. For example „#.0“ formats number to have one decimal place and zero to N digits before decimal point (e.g. „.5“ or „123.5“).
Following code shows how can be formatted a zero (of double type).
[C#]
String.Format("{0:0.0}", 0.0);            // "0.0"
String.Format("{0:0.#}", 0.0);            // "0"
String.Format("{0:#.0}", 0.0);            // ".0"
String.Format("{0:#.#}", 0.0);            // ""

Align numbers with spaces

To align float number to the right use comma „,“ option before the colon. Type comma followed by a number of spaces, e.g. „0,10:0.0“ (this can be used only in String.Format method, not indouble.ToString method). To align numbers to the left use negative number of spaces.
[C#]
String.Format("{0,10:0.0}", 123.4567);    // "     123.5"
String.Format("{0,-10:0.0}", 123.4567);   // "123.5     "
String.Format("{0,10:0.0}", -123.4567);   // "    -123.5"
String.Format("{0,-10:0.0}", -123.4567);  // "-123.5    "

Custom formatting for negative numbers and zero

If you need to use custom format for negative float numbers or zero, use semicolon separator;“ to split pattern to three sections. The first section formats positive numbers, the second section formats negative numbers and the third section formats zero. If you omit the last section, zero will be formatted using the first section.
[C#]
String.Format("{0:0.00;minus 0.00;zero}", 123.4567);   // "123.46"
String.Format("{0:0.00;minus 0.00;zero}", -123.4567);  // "minus 123.46"
String.Format("{0:0.00;minus 0.00;zero}", 0.0);        // "zero"

Some funny examples

As you could notice in the previous example, you can put any text into formatting pattern, e.g. before an usual pattern „my text 0.0“. You can even put any text between the zeroes, e.g. „0aaa.bbb0“.
[C#]
String.Format("{0:my number is 0.0}", 12.3);   // "my number is 12.3"
String.Format("{0:0aaa.bbb0}", 12.3);          // "12aaa.bbb3"


May 11, 2011

Format Strings Explained with ASP.NET 4.0 and C#

What is a Format String?
Format strings are used to format common data types when converting them to strings. An example of this would be converting some data in an integer to a string in the format of currency. The standard numeric format strings allow us to convert numeric data to the following formats:
Name 
Format Specifier 
Currency 
C
Decimal 
D
Exponential 
E
Fixed-point 
F
General 
G
Number 
N
Percent 
P
Round-trip 
R
Hexadecimal 
X


Furthermore, there are also format strings for other types such as dates and times. Some of the datetime formats are as follows:
Format Pattern 
Format Specifier 
Short Date
Long Date 
Full Date Time 
Month Day 
Short Time 
Long Time 
Month Year 

The Syntax
Let's take a look at an example in which we will convert an integer to a string with the formatting of our currency:

int intData = 123456;
//Output currency
Response.Write(intData.ToString("C"));
Response.Write("<br/>"); //new line


This code will output '$123,456.00'. Notice the syntax that we use for the format string. We simply call the ToString method, pass it the format specifier, and it does the rest for us.


Let's take a look at an example where we want to ouput a double as a string with only a specified number of decimal places:

double dblData = 12345.6789;
//Output fixed-point to specific precision


Response.Write(dblData.ToString("F3"));
Response.Write("<br/>"); //new line


This code will output '12345.679'. Notice, to specify the number of decimals places we simply just need to append a number to the format specifier.