Operations on Strings
Operations on Strings
Fundamental Operations on Strings
The Mutability and Immutability of a String
An object is said to be mutable if it can change at will. This means that when something, anything, such as an external action, occurs, the nature (such as structure and/or appearance) of the object changes tremendously (sometimes to brand new object, but we are not studying biology (think of butterflies) or anthropology here). This concept is close to class inheritance where you can get a new class by deriving from an existing class and getting new functionalities from the derived class.
An object is immutable, or not mutable, if its nature cannot change. The only way to get a similar object is only to create a new object that looks, or appears, like the first one.
The String class is one of the largest types in the .NET Framework. It includes many methods to perform all type of operations neccessary on a string. The String type is immutable. This means that every time you perform an operation that modifies a String object, you get a brand new string, not a copy, not a duplicate. If you manipulate many strings in your code, you may thing that you should be concerned with the computer memory (as is the case in other languages such as previous versions of C++ and Pascal). Don't get concerned with memory. The C# compiler takes care of all memory concernes behind the scenes.
Adding Strings
One of the routine operations you can perform on two strings consists of adding one to another, that is, putting one string to the right of another string, to produce a new string made of both. There are two techniques you can use.
To add one string to another, you can use the addition operator as done in arithmetic. Here is an example:
@{
string quote = "Never let your head hang down. Never give up and sit down and grieve. Find another way. And don't pray when it rains if you don't pray when the sun shines.";
string author = "President Nixon";
string quotation = quote + author;
}
In the same way, you can add as many strings as necessary using +. Here is an example:
@{ string quote = "Never let your head hang down. Never give up and sit down and grieve. Find another way. And don't pray when it rains if you don't pray when the sun shines."; string firstName = "Richard"; string middleInitial = "M"; string lastName = "Nixon"; string quotation = quote + " - " + firstName + " " + middleInitial + ". " + lastName; } <div style="width: 400px"> <p>@quotation</p> </div>
Concatenating Some Strings
Besides the addition operator, to formally support string concatenation, the string data type provides the Concat() method that is overloaded in various versions. One of the versions of this method takes two string arguments. Its syntax is:
public static string Concat(string str1, string str2);
This versions takes two strings that should be concatenated. The method returns a new string as the first added to the second. Two imitations of this version use the following versions:
public static string Concat(string str0, string str1, string str2); public static string Concat(string str0, string str1, string str2, string str3);
In each case, the method takes a group of strings and adds them.
Practical Learning: Concatenating Some Strings
@{ ViewBag.Title = "Employee Account Creation"; } <h2 class="text-center">Employee Account Creation</h2> <div class="horizontal-line"></div> @{ int length = 0; int digits = 0; int symbols = 0; int lowercase = 0; int uppercase = 0; string strUsername = string.Empty; string strLastName = string.Empty; string strFirstName = string.Empty; string strMiddleName = string.Empty; string strNewPassword = string.Empty; string strErrorMessage = string.Empty; string strConfirmPassword = string.Empty; if (IsPost) { strFirstName = Request["txtFirstName"].ToString(); strMiddleName = Request["txtMiddleName"].ToString(); strLastName = Request["txtLastName"].ToString(); strNewPassword = Request["txtNewPassword"].ToString(); length = strNewPassword.Length; strConfirmPassword = Request["txtConfirmPassword"].ToString(); if(strMiddleName == "") { strUsername = string.Concat(strLastName, ", ", strFirstName); } else { strUsername = string.Concat(strLastName, ", ", strMiddleName, " ", strFirstName); } for (int i = 0; i < length; i++) { . . . No Change } . . . No Change } } @using (Html.BeginForm()) { . . . No Change }
Compound Concatenation
To add a character or a string to an existing string, use the += operator. When the operator has been used, the string is made of the characters it previously had plus the new character(s). Here is an example:
@{ string quote = "Nihilism is a natural consequence of a culture (or civilization) ruled and regulated by categories that mask manipulation, mastery and domination of peoples and nature."; quote += " - "; quote += "Cornel"; quote += " "; quote += "West"; } <div style="width: 400px"> <p>@quote</p> </div>
Formatting a String
Formatting a string consists of specifying how it would be presented as an object. To support this operation, the string type is equipped with a static method named Format. The String.Format() method is overloaded in various versions; the syntax of the simplest version is:
public static string Format(string format, Object arg0);
This method takes two arguments. The first argument can contain one or a combination of {} operators that include incrementing numbers. The second argument contains one or a combination of values that would be added to the {} operators of the first argument.
If you need two placeholders for values, use the following version of the method:
public static string Format(string format, object arg0, object arg1)
The first argument can contain a string plus {0} and {1} anywhere in the string (but {0} must come before {1}). The second argument will be used in place of {0} in the first argument, and the third argument will be used in place the {1} placeholders.
If you need three placeholders for values, use the following version of the method:
public static string Format(string format, object arg0, object arg1, object arg2)
The first argument can contain a string plus {0}, {1}, and {2} anywhere in the string (but the {0}, {1}, and {2} must appear in that order). The second argument will be used in place of {0} in the first argument, the third argument will be used in place the {1} placeholder, and the fourth argument will be used in place of {2}.
If you need more than three placeholders for values, use the following version of the method:
public static string Format(string format, params object[] args)
The first argument can contain one or a combination of {number} placeholders. The second argument is one or a combination of values that would be orderly added to the {number} placeholders of the first argument.
Practical Learning: Formatting Some Strings
@{ ViewBag.Title = "Employee Account Creation"; } <h2 class="text-center">Employee Account Creation</h2> <div class="horizontal-line"></div> @{ . . . No Change if (IsPost) { strFirstName = Request["txtFirstName"].ToString(); strMiddleName = Request["txtMiddleName"].ToString(); strLastName = Request["txtLastName"].ToString(); strNewPassword = Request["txtNewPassword"].ToString(); length = strNewPassword.Length; strConfirmPassword = Request["txtConfirmPassword"].ToString(); if(strMiddleName == null) { strUsername = string.Format("{0} {1}", strFirstName, strLastName); } else { strUsername = string.Format("{0}, {1} {2}", strLastName, strFirstName, strMiddleName); } . . . No Change } } @using (Html.BeginForm()) { . . . No Change }
String Interpolation
String interpolation consists of starting string formatting with the $ symbol followed by the normal double-quotes that contains one or a combination of {}. Between the curly brackets, type the name of the variable whose values would be displayed. Here are examples:
@{
var employeeNumber = "359-486";
string firstName = "Claire";
dynamic lastName = "Simmons";
String identification = $"{employeeNumber}: {lastName}, {firstName}";
}
<p>Employee Identification: @identification</p>
Practical Learning: Interpoltting Some Strings
@{ ViewBag.Title = "Employee Account Creation"; } <h2 class="text-center">Employee Account Creation</h2> <div class="horizontal-line"></div> @{ . . . No Change if (IsPost) { strFirstName = Request["txtFirstName"].ToString(); strMiddleName = Request["txtMiddleName"].ToString(); strLastName = Request["txtLastName"].ToString(); strNewPassword = Request["txtNewPassword"].ToString(); length = strNewPassword.Length; strConfirmPassword = Request["txtConfirmPassword"].ToString(); if(strMiddleName == null) { strUsername = $"{strFirstName} {strLastName}"; } else { strUsername = $"{strFirstName} {strMiddleName} {strLastName}"; } . . . No Change } } @using (Html.BeginForm()) { . . . No Change }
Sub-Strings
Introduction
A sub-string is a section or part of a string. Obviously, to get a sub-string, you first need an existing string.
Fundamentals of Creating a Sub-String
There are various ways you can create a sub-string from an existing string. As one way, you can retrieve one or more characters from an existing string. To support this, the string class is equipped with a method named Substring() that is overloaded with two versions. The syntax of one is:
public string Substring(int startIndex);
The integer argument specifies the position of the first character from the variable that called the method. The return value is a new string that is made of the characters from startIndex to the end of the string.
Another technique to create a sub-string consists of extracting it from the beginning of an original string. To support this, the string class is equipped with another version of the Substring() method. Its syntax is:
public string Substring(int startIndex, int length);
The first argument specifies the index of the character to start from the string variable that calls this method. The second argument specifies the length of the string.
Practical Learning: Creating Sub-Strings
@{ ViewBag.Title = "Employee Account Creation"; } <h2 class="text-center">Employee Account Creation</h2> <div class="horizontal-line"></div> @{ int length = 0; int digits = 0; int symbols = 0; int lowercase = 0; int uppercase = 0; string strUsername = string.Empty; string strLastName = string.Empty; string strFirstName = string.Empty; string strMiddleName = string.Empty; string strNewPassword = string.Empty; string strErrorMessage = string.Empty; string strConfirmPassword = string.Empty; if (IsPost) { strFirstName = Request["txtFirstName"].ToString(); strMiddleName = Request["txtMiddleName"].ToString(); strLastName = Request["txtLastName"].ToString(); strNewPassword = Request["txtNewPassword"].ToString(); length = strNewPassword.Length; strConfirmPassword = Request["txtConfirmPassword"].ToString(); if(strMiddleName == "") { strUsername = $"{strFirstName.Substring(0, 1)}{strLastName}".ToLower(); } else { strUsername = $"{strFirstName.Substring(0, 1)}{strMiddleName.Substring(0, 1)}{strLastName}".ToLower(); } for (int i = 0; i < length; i++) { if (Char.IsDigit(strNewPassword[i])) { digits++; } if (Char.IsSymbol(strNewPassword[i]) || Char.IsPunctuation(strNewPassword[i])) { symbols++; } if (Char.IsLower(strNewPassword[i])) { lowercase++; } if (Char.IsUpper(strNewPassword[i])) { uppercase++; } } if (string.Compare(strNewPassword, strConfirmPassword) == 0) { strErrorMessage = "Your password will be saved successfully."; } else { strErrorMessage = "The passwords don 't match."; digits = 0; symbols = 0; lowercase = 0; uppercase = 0; strLastName = string.Empty; strUsername = string.Empty; strFirstName = string.Empty; strMiddleName = string.Empty; strNewPassword = string.Empty; strConfirmPassword = string.Empty; } } } @using (Html.BeginForm()) { <table> <tr> <td class="left-col">First Name:</td> <td>@Html.TextBox("txtFirstName", @strFirstName)</td> </tr> <tr> <td>Middle Name:</td> <td>@Html.TextBox("txtMiddleName", @strMiddleName)</td> </tr> <tr> <td>Last Name:</td> <td>@Html.TextBox("txtLastName", @strLastName)</td> </tr> <tr> <td>Username:</td> <td>@Html.TextBox("txtUsername", @strUsername)</td> </tr> </table> <hr /> <table> <tr> <td class="left-col">New Password:</td> <td>@Html.TextBox("txtNewPassword", @strNewPassword)</td> <td>@Html.TextBox("txtCharacters", @length, new { @class = "small-text" }) Characters</td> </tr> <tr> <td>Confirm Password:</td> <td>@Html.TextBox("txtConfirmPassword", @strConfirmPassword)</td> <td> </td> </tr> </table> <table> <tr> <td class="left-col"> </td> <td class="large">@Html.TextBox("txtLowercase", @lowercase, new { @class = "small-text" }) Lowercase Letters</td> <td>@Html.TextBox("txtUppercase", @uppercase, new { @class = "small-text" }) Uppercase Letters</td> </tr> <tr> <td class="left-col"> </td> <td>@Html.TextBox("txtDigits", @digits, new { @class = "small-text" }) Digits</td> <td>@Html.TextBox("txtSymbols", @symbols, new { @class = "small-text" }) Symbols</td> </tr> </table> <div class="horizontal-line"></div> <p class="text-center"><input type="submit" name="btnSubmit" value="Submit" class="btnLarge" /></p> <p>@strErrorMessage</p> }
Looking for a Character or a Sub-String in a String
To assist you with looking for a character or a sub-string within a string, the String class provides a method named Contains. Its syntax is:
public bool Contains(string value)
Unwanted Characters and Sections in a String
Trimming a String
Trimming a string consists of removing empty spaces from it. To let you remove empty spaces from the left side of a string, the String class is equipped with a method named TrimStart. Its syntax is:
public string TrimStart(params char[] trimChars)
To let you remove empty spaces from the right side of a string, the String class provides the TrimEnd method. Its syntax is:
public string TrimEnd(params char[] trimChars)
To let you remove empty spaces from both sides of a string, the String class is equipped with a method named Trim. It is overloaded with two versions. Their syntaxes are:
public string Trim() public string Trim(params char[] trimChars)
Replacing a Character
If you have a string that contains a wrong character, you can either delete that character or replace it with another character of your choice. To support this operation, the String class is equipped with a method named Replace that is overloaded with two versions. One of the versions of the String.Replace() method uses the following syntax:
public string Replace(char oldChar, char newChar);
The first argument of this method is used to identify the sought character. If, and everywhere, that character is found in the string, it would be replaced by the character passed as the second argument.
Replacing a Sub-String
Inside of a string, if you have a combination of consecutive characters you don't want to keep, you can either remove that sub-string or replace it with a new combination of consecutive characters of your choice. To support this operation, the String class provides a version of the Replace() method whose syntax is:
public string Replace(string oldStr, string newStr);
The oldStr argument is the sub-string to look for in the string. Whenever that sub-string is found in the string, it is replaced by the newStr argument.
Practical Learning: Replacing some Sub-Strings
@{ ViewBag.Title = "State Search"; } <h2>Germany: State Search</h2> @{ . . . No Change } @{ int iArea = 0; bool found = false; string strErrorMessage = ""; string strCapital = string.Empty; string strStateName = string.Empty; string strAbbreviation = string.Empty; string strStateLetters = string.Empty; if (IsPost) { if (string.IsNullOrWhiteSpace(Request["txtStateLetters"].ToString())) { strErrorMessage = "You must type a 2-letter abbreviation for a state"; } else { strStateLetters = Request["txtStateLetters"].ToString(); string strReduced = strStateLetters.ToUpper().Replace(" ", ""); for (int i = 0; i < 16; i++) { if (strReduced.Equals(abbreviations[i])) { iArea = areas[i]; strStateName = states[i]; strCapital = capitals[i]; strAbbreviation = abbreviations[i]; found = true; break; } } } if(found == false) { strErrorMessage = "There is no state with those letters."; } } } @using (Html.BeginForm()) { . . . No Change }
@{
ViewBag.Title = "State Search";
}
<h2>State Search</h2>
@{
string[] abbreviations = new string[]
{
"TH", "SL", "NW", "HH", "RP", "NI",
"SH", "BB", "HE", "BE", "ST", "BW",
"BY", "SN", "HB", "MV"
};
string[] states = new string[]
{
"Saarland", "North Rhine-Westphalia", "Thuringia",
"Hamburg", "Rhineland-Palatinate", "Lower Saxony",
"Schleswig-Holstein", "Brandenburg", "Hesse", "Berlin",
"Saxony-Anhalt", "Baden-Württemberg", "Bavaria",
"Saxony", "Bremen", "Mecklenburg-Vorpommern"
};
int[] areas = new int[]
{
16172, 2569, 34085, 755, 19853, 47609, 15799, 29479, 21115, 892, 20446, 35752, 70552, 18416, 419, 23180
};
string[] capitals = new string[]
{
"Saarbrücken", "Düsseldorf", "Erfurt", "", "Mainz","Hanover", "Kiel", "", "Wiesbaden",
"Stuttgart", "Magdeburg", "Munich", "Potsdam", "Dresden", "Bremen", "Schwerin"
};
}
@{
int iArea = 0;
bool found = false;
string strErrorMessage = "";
string strCapital = string.Empty;
string strStateName = string.Empty;
string strAbbreviation = string.Empty;
string strStateLetters = string.Empty;
if (IsPost)
{
if (string.IsNullOrWhiteSpace(Request["txtStateLetters"].ToString()))
{
strErrorMessage = "You must type a 2-letter abbreviation for a state";
}
else
{
strStateLetters = Request["txtStateLetters"].ToString();
string strReduced = strStateLetters.ToUpper().Replace(" ", "").Replace(".", "");
for (int i = 0; i < 16; i++)
{
if (strReduced.Equals(abbreviations[i]))
{
iArea = areas[i];
strStateName = states[i];
strCapital = capitals[i];
strAbbreviation = abbreviations[i];
found = true;
break;
}
}
}
if(found == false)
{
strErrorMessage = "There is no state with those letters.";
}
}
}
@using (Html.BeginForm())
{
<table style="width: 320px;">
<tr>
<td class="left-col">State Letters:</td>
<td>@Html.TextBox("txtStateLetters", "", new { style = "width: 60px" })
<input type="submit" name="btnFind" value="Find" class="left-col" /></td>
</tr>
<tr>
<td>State:</td>
<td>@Html.TextBox("txtAbbreviation", @strAbbreviation, new { style = "width: 40px" })
@Html.TextBox("txtStateName", @strStateName)</td>
</tr>
<tr>
<td>Area:</td>
<td>@Html.TextBox("txtArea", @iArea, new { @class = "medium-text" }) Km<sup>2</sup></td>
</tr>
<tr>
<td>Capital:</td>
<td>@Html.TextBox("txtCapital", @strCapital)</td>
</tr>
</table>
<p>@strErrorMessage</p>
}
Duplicating a String
Copying a String
After declaring and initializing one String variable, you can assign it to another String variable using the assignment operator. Here is an example:
@{
string strPerson = "Charles Stanley";
string strSomebody = strPerson;
}
Assigning one variable to another is referred to as copying it. To formally support this operator, the String class is equipped with the Copy() method. Its syntax is:
public static string Copy(string str);
This method takes as argument an existing String object and copies it, producing a new string. Here is an example:
@{
string strPerson = "Charles Stanley";
string strSomebody = string.Copy(strPerson);
}
Copying To a String
The string.Copy() method is used to copy all characters of one string into another another. To let you copy only a few characters, the String class is equipped with a method named CopyTo. Its syntax is:
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count);
Strings and Methods
Passing a String to a Function or Method
Like a normal value, a string can be passed to a method. When calling the method, you can pass a value for the argument in double-quotes or provide the name of a variable that holds the string.
Returning a String From a Function
You can create a method that returns a string. This is done the same way as with the other classes.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2019, FunctionX | Next |
|