Operations on Text
Operations on Text
Building a String
Introduction
We knowe that the string type is immutable. To let you work on mutable strings, the .NET Framework provides the StringBuilder sealed clas named. The class is created in the System.Text namespace.
An Object to Build a String
To build a string, if you are writing you code in a class, you can include a using System.Text line in the top section of your document. Then, you can declare a StringBuilder variable. If you are writing your code in the HTML side of a webpage, precede the StringBuilder type by its namespace to declare the variable.
To let you start building a string, the StringBuilder class is equipped with various constructors. If you want to work from scratch, use its default constructor. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>Thoughtss</title>
</head>
<body>
@{
System.Text.StringBuilder thoughts = new System.Text.StringBuilder();
}
</body>
</html>
To let you work from a primary string, the class is equipped with a constructor that takes a string as argument. Its syntax is:
public StringBuilder(string value);
Here is an example of using this method to start building a string:
using System.Text; public class Study { public StringBuilder Sociology; public Study() { Sociology = new StringBuilder("Human Interactions"); } }
Adding a String to a Builder
To start building a string, add a character or a word to it. To support this operation, the StringBuilder class is equipped with an overloaded method named Append. This method has a version for every primitive type. For example, the version used to add an integer to a string uses the following syntax:
public StringBuilder Append(int value);
The version of the StringBuilder.Append() method used to add a string uses the following syntax:
public StringBuilder Append(string value);
When you call the StringBuilder.Append() method, if the object is empty, such as if this is the first time you are calling the method on a variable declared using the default constructor, the argument would constitute the primary string of the variable. Based on this, here is an example of starting building a string:
<!DOCTYPE html> <html> <head> <title>Thoughts</title> </head> <body> @{ System.Text.StringBuilder thoughts = new System.Text.StringBuilder(); thoughts.Append("I think NFL Football players are probaly no different than lawyers in terms of attacking opponents and then after the event, shaking hands and going back to a civil normal life."); } </body> </html>
The Value of a Built String
When you declare a StringBuilder variable, you get a String object. As a result, you can use a StringBuilder object where you would use a string value. For example, you can display its value on a webpage. Here is an example:
<!DOCTYPE html> <html> <head> <title>Sociology</title> </head> <body> @{ System.Text.StringBuilder thought = new System.Text.StringBuilder(); thought.Append("I think NFL Football players are probaly no different than lawyers in terms of attacking opponents and then after the event, shaking hands and going back to a civil normal life."); } <p>@thought</p> </body> </html>
This would produce:
Of course, you can also access a StringBuilder object declared in a class.
Adding Strings to a Builder
To add more than one string to a StringBuilder object, you can call the StringBuilder.Append() method. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>Thoughts</title>
</head>
<body>
@{
System.Text.StringBuilder thought = new System.Text.StringBuilder();
thought.Append("I think NFL Football players are probaly no different than lawyers in terms of attacking opponents and then after the event, shaking hands and going back to a civil normal life.");
thought.Append(" - Dr. Robert Huizenga");
}
<p>@thought</p>
</body>
</html>
This would produce:
In the same way, you can keep calling the StringBuilder.Append() to add more strings, each call with the desired value. Here are examples:
using System.Text;
public class ComputerScience
{
public StringBuilder Fields;
public ComputerScience()
{
Fields = new StringBuilder("Information Theory");
Fields.Append(", ");
Fields.Append("Databases");
Fields.Append(", ");
Fields.Append("Articfial Intelligence");
Fields.Append(", ");
Fields.Append("Computer Networking");
Fields.Append(", ");
Fields.Append("Graphics and Visualization");
Fields.Append(", ");
Fields.Append("Computer Security");
Fields.Append(", ");
Fields.Append("Cryptography");
Fields.Append(", and ");
Fields.Append("Software Engineering");
}
}
Remember that you can access the variable as a whole. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>Computer Science Fields</title>
</head>
<body>
@{
ComputerScience studies = new ComputerScience();
}
<p>Computer Science Fields: @studies.Fields.</p>
</body>
</html>
This would produce:
Consider the following classes:
public interface IPolyhedron { string Name { get; } double FactorArea { get; } double FactorVolume { get; } int Faces { get; } int Edges { get; } int Vertices { get; } } public class Tetrahedron : IPolyhedron { public double FactorArea => 1.732051; public double FactorVolume => 0.117851; public string Name => "Tetrahedron"; public int Faces { get; } public int Edges { get; } public int Vertices { get; } public double Edge { get; set; } public Tetrahedron(int faces, int edges, int vertices) { Faces = faces; Edges = edges; Vertices = vertices; } } public class Octahedron : IPolyhedron { public int Faces { get; } public int Edges { get; } public int Vertices { get; } public double Edge { get; set; } public double FactorArea => 3.464102; public double FactorVolume => 0.471405; public string Name => "Octahedron"; public Octahedron(int faces, int edges, int vertices) { Faces = faces; Edges = edges; Vertices = vertices; } }
Remember that the StringBuilder class provides an Append() method for every primitive type. This allows you to add all types of values to a StringBuilder object. You can also pass variables, fields, or properties that hold values. Here are examples:
<!DOCTYPE html> <html> <head> <title>Geometric Volumes</title> </head> <body> @{ IPolyhedron poly = new Tetrahedron(4, 6, 4); System.Text.StringBuilder description = new System.Text.StringBuilder(); description.Append("A "); // Adding a string description.Append(poly.Name); description.Append(" is a polyhedron with "); // Adding an integer description.Append(poly.Faces); description.Append(" faces, "); description.Append(poly.Edges); description.Append(" edges, and "); description.Append(poly.Vertices); description.Append(" vertices. The formula to calculate its surface area is Edge * Edge * "); // Adding a double-precision floating-point number description.Append(poly.FactorArea); description.Append(" and its volume is approximately Edge * Edge * Edge * "); description.Append(poly.FactorVolume); } <p>Description: @description.</p> @{ poly = new Octahedron(8, 12, 6); description = new System.Text.StringBuilder(); description.Append("An "); // Adding a string description.Append(poly.Name); description.Append(" is a polyhedron with "); // Adding an integer description.Append(poly.Faces); description.Append(" faces, "); description.Append(poly.Edges); description.Append(" edges, and "); description.Append(poly.Vertices); description.Append(" vertices. The formula to calculate its surface area is Edge * Edge * "); // Adding a double-precision floating-point number description.Append(poly.FactorArea); description.Append(" and its volume is approximately Edge * Edge * Edge * "); description.Append(poly.FactorVolume); } <p>Description: @description.</p> </body> </html>
This would produce:
Inserting a String
The StringBuilder.Append() method adds a string at the end of the existing string of the variable and produces a new string. The new string is considered a group (or array) of characters. This means that the produced string is not treated as a group of strings but as an array of characters. Each character or symbol occupies a specific position which is its index. The first character is positioned at index 0. The second character is positioned at index 1, and so on.
To let you add a character or string to the beginning, or to insert a character or a string at the beginning of the existing string, the StringBuilder class is equipped with an overloaded method named Insert. Each version of this method takes two arguments. The version used to insert a double-precision number uses the following syntax:
public StringBuilder Insert(int index, double value);
The version used to insert a string uses the following syntax:
public StringBuilder Insert(int index, string value);
The first argument is the index where you want the new value. The characters after that position would be pushed to the right. Here is an example:
<!DOCTYPE html> <html> <head> <title>Computer Science Fields</title> </head> <body> @{ ComputerScience studies = new ComputerScience(); } <p>Computer Science Fields: @studies.Fields.</p> @{ studies = new ComputerScience(); studies.Fields.Insert(0, "Computational Science, "); } <p>Computer Science Fields: @studies.Fields.</p> @{ studies.Fields.Insert(54, "Distributed Systems, "); } <p>Computer Science Fields: @studies.Fields.</p> </body> </html>
This would produce:
Encoding and Decoding Text
Introduction
The Internet consists of honoring requests for document publication, from one source that can be a browser or a webserver to a destination that too can be a browser or a webserver. The documents primarily contain text and such text can include various types of characters. A document may include some special symbols such as those used in HTML. Examples are < (the less than symbol), > (the greater than symbol), ' (the single quote), " (the double-quote), etc. Sometimes, those same symbols may be included in the text that must be sent. In some cases, you may want to publish some characters from various languages such as Greek, French, German, etc. If you don't do a good job, you may get corrupted or unpredictable results. To faithfully produce a document, either the webserver may use some algorithms to analyze, check, and convert the document somehow, or you can give your own special instructions to the webserver. You have various options.
HTML Encoding
Encoding consists of checking a piece of text that must be transmitted so that some symbols or reserved characters must be changed without losing their meaning. Both IIS (Microsoft Internet Information Services) and ASP.NET provide various means to encode text. The IIS library includes a class named Server. That class is available in the System.Web namespace with the same name. The class contains an overloaded method named HtmlEncode. The syntax of one of the versions is:
public static string HtmlEncode(string value)
As another technique, the System.Web namespace contains a class named HttpUtility. That class is available in the System.Web namespace as the HttpServerUtility class. The class contains an overloaded method named HtmlEncode. One of its syntaxes uses the following version:
public static string HtmlEncode(string value)
In both cases, pass a string as argument. The method would check every symbol in the string. If a symbol is a special character, it would be encoded. If the symbol is not a special character, it would be kept. At the end, the method returns a new string where special characters have been converted. Here is an example:
<!DOCTYPE html> <html> <head> <title>Employee Login</title> </head> <body> <h1>Employee Login</h1> @{ string strEncodedUsername = string.Empty; string strEncodedPassword = string.Empty; string strOriginalUsername = "john&peter"; string strOriginalPassword = "P@s$w>15But<20W0rd$"; if (IsPost) { strOriginalUsername = Request["txtOriginalUsername"]; strOriginalPassword = Request["txtOriginalPassword"]; strEncodedUsername = Server.HtmlEncode(strOriginalUsername); strEncodedPassword = HttpUtility.HtmlEncode(strOriginalPassword); } } <form name="frmExercise" method="post"> <table> <tr> <td>Username:</td> <td><input type="text" name="txtOriginalUsername" style="width: 175px" value=@strOriginalUsername /></td> </tr> <tr> <td>Password: </td> <td><input type="text" name="txtOriginalPassword" style="width: 175px" value=@strOriginalPassword /></td> </tr> <tr> <td> </td> <td><input type="submit" name="btnSubmit" value="Submit" /></td> </tr> <tr> <td>Encoded Username:</td> <td>@strEncodedUsername</td> </tr> <tr> <td>Encoded Password:</td> <td>@strEncodedPassword</td> </tr> </table> </form> </body> </html>
After typing some text and clicking the button:
Encoding Text
The .NET Framework provides many means to format text. This is mostly supported in the System.Text namespace. This namespace includes a class named Encoder. This class considers one or an array of characters provided in Unicode format. The class would convert the character(s) to the right or necessary format.
The primary class used to encode a character is named Encoding. This is an abstract class that receives a character as a byte type. analyzes it, and produces the necessary result. Encoding is an abstract class. A class derived from it would do the actual job. Because human languages use different ways to represent their particular characters, the .NET Framework provides various classes for encoding.
Latin-based languages such as English primarily use 8 bits to represent their characters. To support this format, the .NET Framework provides a class named UTF8Encoding. This class is derived from Encoding. To prepare to encode a character, declare a variable of type UTF8Encoding . The class is equipped with three constructors, including the dfault. Therefore, to starting encoding, you can declare a UTF8Encoding variable using its default constructor. If you are working in in a class, you can include the namespace in the top section of the document. Here is an example:
using System.Text; public class Correspondance { UTF8Encoding u8e = new UTF8Encoding(); }
If you are working in the the HRML side of a webpage, use the class but qualify it with its namespace. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>Special Correspondence</title>
</head>
<body>
@{
System.Text.UTF8Encoding u8e = new System.Text.UTF8Encoding();
}
</body>
</html>
To let you specify the character or the string to be encoded, the Encoding class is equipped with an overloaded method named GetBytes that its child classes inherit. This method provides versions that take a string, an array of characters, a sub-string from an existing string delimited by a starting index, and many oters. The version that takes a string uses the following syntax:
public virtual byte[] GetBytes(string s);
This method considers every one of the characters passd through the argument. It converts each character to its ASCII equivalent and produces an array that contains the ASCII numbers of the characters as items. Here is an example:
<!DOCTYPE html> <html> <head> <title>Special Correspondence</title> </head> <body> @{ System.Text.UTF8Encoding u8e = new System.Text.UTF8Encoding(); byte[] characters = u8e.GetBytes("Copyright ©, 2018"); } <ul> @for (int i = 0; i < characters.Length - 1; i++) { <li>@characters[i]</li> } </ul> </body> </html>
This would produce:
HTML Decoding
Obviously when an encoded string gets to its destination, it must be restored to its original version. Decoding consists or restoring an encoded string. To support this operation, both the Server and the HttpServerUtility classes contain an overloaded method named HtmlDecode. The common syntax of this method is:
public static string HtmlDecode(string value)
This time too, pass a string as argument. The method would try to identify every combination of characters that may represent a special character. When such a combination is encountered, the method would convert the combination to the appropriate symbol. For example, a combination of & would be converted to the ampersand. Here are examples of calling the method:
<!DOCTYPE html> <html> <head> <title>Employee Login</title> </head> <body> <h1>Employee Login</h1> @{ string strEncodedUsername = string.Empty; string strEncodedPassword = string.Empty; string strDecodedUsername = string.Empty; string strDecodedPassword = string.Empty; string strOriginalUsername = "john&peter"; string strOriginalPassword = "P@s$w>15But<20W0rd$"; if (IsPost) { strOriginalUsername = Request["txtOriginalUsername"]; strOriginalPassword = Request["txtOriginalPassword"]; strEncodedUsername = Server.HtmlEncode(strOriginalUsername); strEncodedPassword = HttpUtility.HtmlEncode(strOriginalPassword); strDecodedUsername = HttpUtility.HtmlDecode(strEncodedUsername); strDecodedPassword = Server.HtmlDecode(strEncodedPassword); } } <form name="frmExercise" method="post"> <table> <tr> <td>Username:</td> <td><input type="text" name="txtOriginalUsername" style="width: 175px" value=@strOriginalUsername /></td> </tr> <tr> <td>Password: </td> <td><input type="text" name="txtOriginalPassword" style="width: 175px" value=@strOriginalPassword /></td> </tr> <tr> <td> </td> <td><input type="submit" name="btnSubmit" value="Submit" /></td> </tr> <tr> <td>Encoded Username:</td> <td>@strEncodedUsername</td> </tr> <tr> <td>Encoded Password:</td> <td>@strEncodedPassword</td> </tr> <tr> <td>Decoded Username:</td> <td>@strDecodedUsername</td> </tr> <tr> <td>Decoded Password:</td> <td>@strDecodedPassword</td> </tr> </table> </form> </body> </html>
After clicking the button:
An HTML String
Introduction
To accommodate some of the needs of strings in ASP.NET, the System.Web namespace includes a class named HtmlString.
HtmlString is a small class that contains only one constructor and two methods. The constructor uses the following syntax:
public HtmlString(string value)
Therefore, to create a string from HtmlString, you can declare a variable using its constructor and pass a double-quoted string as argument. Here is an example:
@{
HtmlString strCountry = new HtmlString("After all, who can blame a country for being able to take advantage of another country for the benefit of its citizens? - Donald Trump, President of the United States");
}
You can primarily use an HtmlString variable as a string, such to display its value. Here is an example:
@{
HtmlString quote = new HtmlString("After all, who can blame a country for being able to take advantage of another country for the benefit of its citizens? - Donald Trump, President of the United States");
}
<p>Country: @quote</p>
To let you convert an HtmlString object to a string value, the class overrides the ToString() method. The string returned by this method is encoded.
Decoding an HTML String
The HtmlString class always considers that a string given to it is already encoded, or the string is provided in encoded format. This means that this class will not encode a string given to it, even if the string contains special characters. Consider the following example:
<!DOCTYPE html>
<html>
<head>
<title>Employee Login</title>
</head>
<body>
<h1>Employee Login</h1>
@{
HtmlString strEncodedUsername = null;
HtmlString strEncodedPassword = null;
string strOriginalUsername = "john&peter";
string strOriginalPassword = "P@s$w>15But<20W0rd$";
if (IsPost)
{
strOriginalUsername = Request["txtOriginalUsername"];
strOriginalPassword = Request["txtOriginalPassword"];
strEncodedUsername = new HtmlString(strOriginalUsername);
strEncodedPassword = new HtmlString(strOriginalPassword);
}
}
<form name="frmExercise" method="post">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="txtOriginalUsername" style="width: 175px" value=@strOriginalUsername /></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="text" name="txtOriginalPassword" style="width: 175px" value=@strOriginalPassword /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="btnSubmit" value="Submit" /></td>
</tr>
<tr>
<td>Encoded Username:</td>
<td>@strEncodedUsername</td>
</tr>
<tr>
<td>Encoded Password:</td>
<td>@strEncodedPassword</td>
</tr>
</table>
</form>
</body>
</html>
After clicking the button:
On the other hand, when you ask the HtmlString class to produce a string, it will try to decode it. This means that it will proceed with the string as we described for the Server.HtmlDecode() and the HttpUtility.HtmlDecode() methods. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>Employee Login</title>
</head>
<body>
<h1>Employee Login</h1>
@{
HtmlString strEncodedUsername = null;
HtmlString strEncodedPassword = null;
string strOriginalUsername = "john&peter";
string strOriginalPassword = "P@s$w>15But<20W0rd$";
if (IsPost)
{
strOriginalUsername = Request["txtOriginalUsername"];
strOriginalPassword = Request["txtOriginalPassword"];
strEncodedUsername = new HtmlString(strOriginalUsername);
strEncodedPassword = new HtmlString(strOriginalPassword);
}
}
<form name="frmExercise" method="post">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="txtOriginalUsername" style="width: 200px" value=@strOriginalUsername /></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="text" name="txtOriginalPassword" style="width: 200px" value=@strOriginalPassword /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="btnSubmit" value="Submit" /></td>
</tr>
<tr>
<td>Encoded Username:</td>
<td>@strEncodedUsername</td>
</tr>
<tr>
<td>Encoded Password:</td>
<td>@strEncodedPassword</td>
</tr>
</table>
</form>
</body>
</html>
After clicking the button:
|
||
Previous | Copyright © 2017-2019, FunctionX | Next |
|