0% found this document useful (0 votes)
323 views36 pages

String Functions in C#

The document discusses various string manipulation functions in C# including trimming whitespace from strings, padding strings to a certain length, converting case, concatenating strings, inserting/removing substrings, searching/replacing text, and locating text within a string. It provides examples of using methods like Trim, PadLeft, ToUpper, Concat, Insert, Remove, Substring, IndexOf, Replace, and Contains.

Uploaded by

FidelRomasanta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
323 views36 pages

String Functions in C#

The document discusses various string manipulation functions in C# including trimming whitespace from strings, padding strings to a certain length, converting case, concatenating strings, inserting/removing substrings, searching/replacing text, and locating text within a string. It provides examples of using methods like Trim, PadLeft, ToUpper, Concat, Insert, Remove, Substring, IndexOf, Replace, and Contains.

Uploaded by

FidelRomasanta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 36

C# STRING FORMATTING

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"

It is important to note that the Trim methods return a new string


with whitespace removed. The original string is unaffected.
string original = " BlackWasp ";
string trimmed = original.Trim();
Console.WriteLine(original); // Outputs " BlackWasp "
Console.WriteLine(trimmed); // Outputs "BlackWasp"
PADDING
• The String class provides two methods for padding, where
spaces are added to the left or right of a string to achieve a
desired length. This is useful when producing fixed-width
columns of information. The PadLeft method adds spaces to the
left of a string and the PadRight add them to the right. An
integer argument indicates how long the resultant string should
be. If the original string is longer than the parameter value
indicates, the resultant string will be the same as the original.
Padding (cont…)
Example:
string value1 = "£1.00";
string value2 = "£10.00";
string value3 = "£100.00";
// Output a right-aligned column
Console.WriteLine(value1.PadLeft(8)); // Outputs " £1.00"
Console.WriteLine(value2.PadLeft(8)); // Outputs " £10.00"
Console.WriteLine(value3.PadLeft(8)); // Outputs " £100.00"
Padding (cont…)
Example:
// Output a left-aligned column
Console.WriteLine(value1.PadRight(8)); // Outputs "£1.00 "
Console.WriteLine(value2.PadRight(8)); // Outputs "£10.00 "
Console.WriteLine(value3.PadRight(8)); // Outputs "£100.00 "

// Trying to pad a string that is too long


Console.WriteLine(value1.PadRight(3)); // Outputs "£1.00"
Padding (cont…)
• The padding functions can be called with a second argument.
This parameter is a char value holding a character that is used
instead of the default whitespace padding character.
Example:
string value = "£1.00";
Console.WriteLine(value.PadLeft(8,'.')); // Outputs "...£1.00"

Console.WriteLine(value.PadRight(8,'_')); // Outputs "£1.00___"


TEXT CASE CONVERSION
•The String class allows strings to be converted to upper
or lower case text using the user's local culture settings
to ensure correct text conversion for various languages.
The methods are named ToLower and ToUpper. string
webSite = “MinSCAT";
Console.WriteLine(webSite.ToLower()); // Outputs “minscat"
Console.WriteLine(webSite.ToUpper()); // Outputs “MINSCAT"
STRING CONCATENATION
• String
concatenation is the act of combining two strings by
adding the contents of one string to the end of another. Using
the concatenation operator (+). We used the following
example:
string start = "This is a ";
string end = "concatenated string!";
string concat = start + end; //concat = "This is a concatenated string!"
String Concatenation (cont…)
•The Concat method allows many strings to be
passed as arguments. The strings are joined
together and a new, concatenated string is
returned:
string start = "This is a ";
string end = "concatenated string!";
string concat = string.Concat(start, end);
INSERTING STRINGS INTO STRINGS
• Method that inserts one string into the middle of another. The
Insert method acts upon an existing string variable or literal
and requires two parameters. The first is an integer that
indicates the position where the second string is to be inserted.
This integer counts characters from the left with zero indicating
that the insertion will be at the beginning of the string. The
second parameter is the string to be inserted.
string str1 = "Juan Cruz";
string str2 = "dela ";
Console.WriteLine(str1.Insert(5, str2));
// Outputs: “Juan dela Cruz."
REMOVING CHARACTERS FROM A STRING
• The Remove method allows characters to be deleted from a string,
shortening the string accordingly. There are two overloads
available. The first requires a single parameter to indicate the start
position for the character removal. The second overload adds a
second parameter specifying how many characters to delete. Any
further characters are unaffected.
string sample = "The quick brown fox jumps over the lazy dog.";
string result = sample.Remove(16); // result = "The quick brown "

result = sample.Remove(16, 24); // result = "The quick brown dog."


EXTRACTING TEXT FROM A STRING
• TheString class provides a useful function to extract a piece of text
from the middle of a string. This method has two overloads that are
very similar to those of the Remove method. However, rather than
removing the middle section of the string and keeping the start and
end, the Substring method discards the start and end and returns the
middle section. The following code illustrates this using the same
parameters as the previous example.
string sample = "The quick brown fox jumps over the lazy dog.";
string result = sample.Substring(16); // result = "fox jumps over the lazy dog."
result = sample.Substring(16, 24); // result = "fox jumps over the lazy "
SEARCH AND REPLACE
• All modern word processors and text editors include a search and
replace function that permits a specified piece of text to be
substituted with a second string. This functionality is provided by the
Replace method. The method accepts two parameters. The first is
the string to search for and the second is the string to use as a
substitute. When executed, all instances of the first string are
automatically replaced.
string sample = “I hate you.";
string result = sample.Replace(“hate", “love");
// result = “I love you."
COPYING STRINGS
•The final simple string manipulation function to be
considered in this article is the Copy method. This
method creates a copy of an existing string. It provides
the same functionality as assigning to a string directly.
string sample = "The brown fox.";
string result = string.Copy(sample);
// result = "The brown fox."
RETRIEVING A STRING'S LENGTH
•It is often necessary to check the length of a string,
particularly to validate a user's input. The String class
provides a property named Length that gives us this
information. The property returns an integer
representing the number of characters present.
string animal = "Dog";
int result;
result = animal.Length; // result is 3
result = "Elephant".Length; // result is 8
LOCATING TEXT WITHIN A STRING
• This can be achieved with the IndexOf and LastIndexOf methods.
• IndexOf takes a parameter containing a string to search for. If this exists
within the main string the position of the first occurrence is returned. This
position is known as the index and is an integer indicating the number of
characters between the start of the string and the found text. If the
search term appears at the start of the string the index is zero. Should
the sub-string not exist within the main string the method returns -1.
• LastIndexOf is similar to IndexOf. However, instead of returning the index
of the first occurrence of the search term, LastIndexOf returns the
position of the last occurrence.
Locating Text Within a String (cont…)
string phrase = "The quick brown fox jumps over the lazy dog.";
int result;
result = phrase.IndexOf("brown"); // result is 10
result = phrase.LastIndexOf("dog"); // result is 40
result = phrase.IndexOf("green"); // result is -1
result = phrase.LastIndexOf("blue"); // result is -1
Locating Text Within a String (cont…)
• IndexOf and LastIndexOf can be limited further by specifying a
start position for the search. With IndexOf only occurrences of the
specified sub-string at or to the right of this position are found.
string phrase = "The quick brown fox jumps over the lazy dog.";
int result;
result = phrase.IndexOf("he"); // result is 1
result = phrase.IndexOf("he", 1); // result is 1
result = phrase.IndexOf("he", 2); // result is 32
result = phrase.LastIndexOf("he"); // result is 32
result = phrase.LastIndexOf("he",33); // result is 32
result = phrase.LastIndexOf("he",32); // result is 1
Locating Text Within a String (cont…)
•This method return the Substring.
string.Substring(int startingIndex, [int charLength]);
string a=”MinSCAT”;
Console.WriteLine(a.Substring(3)); //OUTPUT: SCAT
Console.WriteLine (a.Substring(1,4)); //OUTPUT: inSC
STARTSWITH AND ENDSWITH
• StartsWith and EndsWith allow you to determine if a string starts or
ends with a specific series of characters. Both methods accept an
argument containing the string to match and return a Boolean value
indicating the result. These methods are case-sensitive.
string phrase = "The quick brown fox jumps over the lazy dog.";
bool result;
result = phrase.StartsWith("The quick"); // result is true
result = phrase.StartsWith("lazy dog."); // result is false
result = phrase.EndsWith("lazy dog."); // result is true
result = phrase.EndsWith("The quick"); // result is false
CONTAINS METHOD
• The final string function considered in this article is Contains.
Introduced in version 2.0 of the .NET framework, it operates in
a similar manner to StartsWith and EndsWith but checks if the
specified search term exists at any position within the main
string.
string phrase = “MinSCAT";
bool result;
result = phrase.Contains(“CAT"); // result is true
result = phrase.Contains(“dog"); // result is false
FORMATTING DATA FOR DISPLAY
• For example, the following statement converts numberInteger to a
string and displays it in displayTextBox.Text.
txtAmount.Text = numberInteger.ToString();

• 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

You might also like