To Lecture Notes
IT 230 -- 5/6/09
The Split Method
- The Split method of the string class splits up a line into
an array of fields according to a specified delimiter.
// Example 1.
string line = Alice,F,21;
fields[ ] = line.Split(',');
litDisplay.Text = <p>Name: + fields[0] +
; Gender: + fields[1] +
; Age: + fields[2] + </p>;
Format Strings
- Use format strings to control how variable values are formatted.
- Here are some examples:
// Example 2.
string s = abc;
int n = 234;
double x = 3.14259;
litDisplay.Text = string.Format(/{0}/{1}/{2}/, s, n, x);
Resulting text in literal control:
/abc/234/3.14259/
{2} in a format string means substitute argument 2 into the output string.
(Start with 0 when counting arguments.)
// Example 3.
double gpa = 3.4587654;
litDisplay.Text = string.Format(Your gpa is {0,4:#0.00}., gpa);
{0, 4:#0.00} in a format string means use argument 0, field width = 4,
show two digits after the decimal point. Show the 0 to the left of the
decimal point, even if the value is less than 1.
// Example 4.
string s = apple;
litDisplay.Text = string.Format(/{0,-7}/, s);
{0,-7} means use argument 0. The -7 means left justify within a field
width of 7.
Practice Problem
- Write an ASP.Net application that reads lines from the input file
persons.txt, splits each line into fields with
the Split method, and uses the string Format method to line up the output
in columns with a Literal control within pre tags. Ans:
<%@ Page Language=C# %>
<%@ Import Namespace=System.IO %>
<script runat=server>
public void Page_Load(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(c:/Database/persons3.txt);
litDisplay.Text = Name Gender Age<br /> +
======== ====== ====<br />;
while (sr.Peek() > -1)
{
string line = sr.ReadLine();
string[] fields = line.Split(',');
string name = fields[0];
string gender = fields[1];
int age = int.Parse(fields[2]);
litDisplay.Text +=
string.Format({0,-8} {1,1} {2,-3}<br />,
name, gender, age);
}
}
</script>
<!DOCclass html PUBLIC -//W3C//DTD XHTML 1.0 Transitional//EN
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
<html xmlns=http://www.w3.org/1999/xhtml >
<head runat=server>
<title>Untitled Page</title>
</head>
<body>
<form id=form1 runat=server>
<div>
<pre style=font-family:Lucida Console; font-weight:bold>
<asp:Literal ID=litDisplay runat=server></asp:Literal>
</pre>
</div>
</form>
</body>
</html>
Examples for Project 5
- Look at Example 49. It shows how to format the
displayed data into columns.