String Functions in C#
String Functions in C#
FUNCTIONS
STRING CLASS
TRIMMING
• String/text inputted by users can include additional
whitespace at the start or the end of the string. Often you will
want to remove such excess spaces. The String class provides
three methods for doing so. The TrimStart and TrimEnd methods
remove whitespace from either the start or the end of a string.
The Trim method combines the two functions by removing
leading and trailing whitespace with a single call. string
inputted = " BlackWasp ";
Trimming (cont…)
Example:
Console.WriteLine(inputted.TrimStart()); // Outputs "BlackWasp "
Console.WriteLine(inputted.TrimEnd()); // Outputs " BlackWasp"
Console.WriteLine(inputted.Trim()); // Outputs "BlackWasp"
• You can use the format specifier codes to format the display of
output.
txtPrice.Text = (quantityInteger * priceDecimal).ToString("C");
• Display as numeric.
txtDiscount.Text = discountDecimal.ToString("N");
Formatting Data for Display (cont…)
Formatting Data for Display (cont…)
Examples:
Formatting Data for Display (cont…)
THE MESSAGEBOX OBJECT
THE TEXTMESSAGE STRING
•The message string you display may be a string literal
enclosed in quotes or a string variable. You also may
want to concatenate several items, for example,
combining a literal with a value from a variable. If the
message you specify is too long for one line, it will wrap
to the next line.
THE TITLEBAR TEXT
•The string that you specify for TitlebarText will appear
in the title bar of the message box. If you choose the
first form of the Show method, without the TitlebarText,
the title bar will appear empty.
MESSAGEBOXBUTTONS
• You specify the buttons using the MessageBoxButtons constants from
the MessageBox class. The choices are
OK
OKCancel
RetryCancel
YesNo
YesNoCancel and
AbortRetryIgnore.
• The default for the Show method is OK, so unless you specify
otherwise, you will get only the OK button in your message box.
MESSAGEBOXICON
• Constants for MessageBoxIcon
Asterisk
Error
Exclamation
Hand
Information
None
Question
Stop
Warning
HANDLING EXCEPTIONS
• When you allow users to input numbers and use those numbers
in calculations, lots of things can go wrong. The Parse methods,
int.Parse and decimal.Parse , fail if the user enters nonnumeric
data or leaves the text box blank. Or your user may enter a
number that results in an attempt to divide by zero. Each of
those situations causes an exception to occur, or, as
programmers like to say, throws an exception .
TRY/CATCH BLOCKS
• To trap or catch exceptions, enclose any statement(s) that
might cause an error in a try/catch block . If an exception
occurs while the statements in the try block are executing,
program control transfers to the catch block; if a finally
statement is included, the code in that section executes last,
whether or not an exception occurred.
THE TRY BLOCK—GENERAL FORM
THE TRY BLOCK—EXAMPLE
THE EXCEPTION CLASS