Programming Blog

Simple but potentially useful – A collection of random programming stuffs

Archive for the ‘Console Application’ Category

String Class

Posted by letmetutoryou on January 30, 2009

In C#, the string type is used for processing multiple character Unicode character data. (The char type, by comparison, is a value type that handles single characters.)

The type name string is a shortened name for the System.String class. The compiler can process this shortened form; therefore string and System.String can be used interchangeably.

The String class represents an immutable string of characters. An instance of String is immutable: the text of a string cannot be modified after it has been created. Methods that might appear at first sight to modify a string value actually return a new instance of string that contains the modification.

The StringBuilder class is often used in partnership with the String class. A StringBuilder builds an internally modifiable string that can be converted into an immutable String when complete. StringBuilder removes the need to repeatedly create temporary immutable Strings and can provide improved performance.

The System.String class has many methods. I will list some of the more useful methods. For further details, consult the .NET Framework software development kit (SDK) Help documents.

Common String Methods, Operators, and Properties

Brackets [ ]

You can extract a single character at a given position in a string by using the string name followed by the index in brackets ([ and ]). This process is similar to using an array. The first character in the string has an index of zero. The following code provides an example:

string s = “Alphabet”;

char firstchar = s[2]; // ‘p’

Strings are immutable, so assigning a character by using brackets is not permitted. Any attempt to assign a character to a string in this way will generate a compile-time error, as shown:

s[2] = ‘*’; // Not valid

Insert Method

If you want to insert characters into a string variable, use the Insert instance method to return a new string with a specified value inserted at a specified position in this string. This method takes two parameters: the position of the start of the insertion and the string to insert. The following code provides an example:

string s = “C is great!”;

s = s.Insert(2, “Sharp “);

Console.WriteLine(s); // C Sharp is great!

Length Property

The Length property returns the length of a string as an integer, as shown:

string msg = “Hello”;

int slen = msg.Length; // 5

Copy Method

The Copy class method creates a new string by copying another string. The Copy method makes a duplicate of a specified string. The following code provides an example:

string s1 = “Hello”;

string s2 = String.Copy(s1);

Concat Method

The Concat class method creates a new string from one or more strings or objects represented as strings. The following code provides an example:

string s3 = String.Concat(“a”, “b”, “c”, “d”, “e”, “f”, “g”);

The + operator is overloaded for strings, so the example above can be re-written as follows:

string s = “a” + “b” + “c” + “d” + “e” + “f” + “g”;

Console.WriteLine(s);

Trim Method

The Trim instance method removes all of the specified characters or white space from the beginning and end of a string. The following code provides an example:

string s = ” Hello “;

s = s.Trim();

Console.WriteLine(s); // “Hello”

ToUpper and ToLower Methods

The ToUpper and ToLower instance methods return a string with all characters converted to uppercase and lowercase, respectively, as shown:

string sText = “How to Succeed “;

Console.WriteLine(sText.ToUpper()); // HOW TO SUCCEED

Console.WriteLine(sText.ToLower()); // how to succeed

String Comparisons

You can use the == and != operators on string variables to compare string contents.

Equals Method

The System.String class contains an instance method called Equals, which can be used to compare two strings for equality. The method returns a bool value that is true if the strings are the same and false otherwise. This method is overloaded and can be used as an instance method or a static method. The following example shows both forms.

string s1 = “Welcome”;

string s2 = “Welcome”;

if (s1.Equals(s2))

Console.WriteLine(“The strings are the same”);

if (String.Equals(s1,s2))

Console.WriteLine(“The strings are the same”);

Compare Method

The Compare method compares two strings lexically; that is, it compares the strings according to their sort order. The return value from Compare is as follows:

  • A negative integer if the first string comes before the second
  • 0 if the strings are the same
  • A positive integer if the first string comes after the second

string s1 = “Tintinnabulation”;

string s2 = “Velocipede”;

int comp = String.Compare(s1,s2); // Negative return

By definition, any string, including an empty string, compares greater than a null reference, and two null references compare equal to each other. Compare is overloaded. There is a version with three parameters, the third of which is a bool value that specifies whether the case should be ignored in the comparison. The following example shows a case-insensitive comparison:

s1 = “cabbage”;

s2 = “Cabbage”;

comp = String.Compare(s1, s2, true); // Ignore case

Locale-Specific Compare Options

The Compare method has overloaded versions that allow string comparisons based on language-specific sort orders. This can be useful when writing applications for an international market. Further discussion of this feature is beyond the scope of the course. For more information, search for “System.Globalization namespace” and “CultureInfo class” in the .NET ramework SDK Help documents.

String Comparison Operators

The == and != operators are overloaded for the String class. You can use these operators to examine the contents of strings.

string a = “Test”;

string b = “Test”;

if (a == b) … // Returns true

The following operators and methods are equivalent:

  • The == operator is equivalent to the String.Equals method.
  • The != operator is equivalent to the !String.Equals method.

The other relational operators (<, >, <=, and >=) are not overloaded for the String class.

Posted in C#, Console Application | Tagged: , , , , , , , , , , , , | Leave a Comment »

Basic Input/Output operations in C#

Posted by letmetutoryou on December 22, 2008

This blog I will show how to perform command-based input/output operations in C# by using the Console class. I will show you how to display information by using the Write and WriteLine methods, and how to gather input information from the keyboard by using the Read and ReadLine methods.

 

The Console Class

The Console class provides a C# application with access to the standard input, standard output, and standard error streams. Standard input is normally associated with the keyboard—anything that the user types on the keyboard can be read from the standard input stream. Similarly, the standard output stream is usually directed to the screen, as is the standard error stream.

These streams and the Console class are only meaningful to console applications. These are applications that run in a Command window.

 
Write and WriteLine Methods

You can use the Console.Write and Console.WriteLine methods to display information on the console screen. These two methods are very similar; the

main difference is that WriteLine appends a new line/carriage return pair to the end of the output, and Write does not. Both methods are overloaded. You can call them with variable numbers and types of parameters. For example, you can use the following code to write “99″ to the screen:

Console.WriteLine(99);

You can use the following code to write the message “Hello, World” to the screen:

Console.WriteLine(“Hello, World”);

 
Text Formatting

You can use more powerful forms of Write and WriteLine that take a format string and additional parameters. The format string specifies how the data is

output, and it can contain markers, which are replaced in order by the parameters that follow. For example, you can use the following code to display the message “The sum of 100 and 130 is 230″:

Console.WriteLine(“The sum of {0} and {1} is {2}”, 100, 130, 100+130);

You can use the format string parameter to specify field widths and whether values should be left or right justified in these fields, as shown in the following code:

Console.WriteLine(“\”Left justified in a field of width 10:{0, -10}\”", 99);

Console.WriteLine(“\”Right justified in a field of width 10:{0,10}\”", 99);

This will display the following on the console:

“Left justified in a field of width 10: 99 “

“Right justified in a field of width 10: 99″

 
You can use the backward slash (\) character in a format string to turn off the special meaning of the character that follows it. For example, “\{” will cause a literal “{” to be displayed, and “\\” will display a literal “\”. You can use the at sign (@) character to represent an entire string verbatim. For example, @”\\server\share” will be processed as \\server\share.

 
Numeric Formatting

You can also use the format string to specify how numeric data is to be formatted. The full syntax for the format string is {N,M:FormatString}, where N is the parameter number, M is the field width and justification, and FormatString specifies how numeric data should be displayed. The table below summarizes the items that may appear in FormatString. In all of these formats, the number of digits to be displayed, or rounded to, can optionally be specified.

 

 

Item Meaning
C Display the number as currency, using the local currency symbol and conventions.
D Display the number as a decimal integer.
E Display the number by using exponential (scientific) notation.
F Display the number as a fixed-point value.
G Display the number as either fixed point or integer, depending on which format is the most compact.
N Display the number with embedded commas.
X Display the number by using hexadecimal notation.

 

The following code shows some examples of how to use numeric formatting:

 
Console.WriteLine(“Currency formatting – {0:C} {1:C4}”, 88.8,-888.8);

Console.WriteLine(“Integer formatting – {0:D5}”, 88);

Console.WriteLine(“Exponential formatting – {0:E}”, 888.8);

Console.WriteLine(“Fixed-point formatting – {0:F3}”,888.8888);

Console.WriteLine(“General formatting – {0:G}”, 888.8888);

Console.WriteLine(“Number formatting – {0:N}”, 8888888.8);

Console.WriteLine(“Hexadecimal formatting – {0:X4}”, 88);

 
When the previous code is run, it displays the following:

 
Currency formatting – $88.80 ($888.8000)

Integer formatting – 00088

Exponential formatting – 8.888000E+002

Fixed-point formatting – 888.889

General formatting – 888.8888

Number formatting – 8,888,888.80

Hexadecimal formatting – 0058

 
Read and ReadLine Methods

You can obtain user input from the keyboard by using the Console.Read and Console.ReadLine methods.

 
The Read Method

Read reads the next character from the keyboard. It returns the int value –1 if there is no more input available. Otherwise it returns an int representing the character read.

 
The ReadLine Method

ReadLine reads all characters up to the end of the input line (the carriage return character). The input is returned as a string of characters. You can use the following code to read a line of text from the keyboard and display it to the screen:

 
string input = Console.ReadLine( );

Console.WriteLine(“{0}”, input);

Posted in C#, Console Application | Tagged: , , , , , , , , , , , , , , | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.