<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>C# Help &#187; Strings</title>
	<atom:link href="http://www.csharphelp.com/tag/strings/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.csharphelp.com</link>
	<description>C# Tutorial and Guides</description>
	<lastBuildDate>Tue, 07 Feb 2012 01:03:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>C# Strings &#8211; Getting Started with Strings</title>
		<link>http://www.csharphelp.com/2011/06/c-strings-getting-started-with-strings/</link>
		<comments>http://www.csharphelp.com/2011/06/c-strings-getting-started-with-strings/#comments</comments>
		<pubDate>Tue, 21 Jun 2011 06:26:03 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Stringbuilder]]></category>
		<category><![CDATA[Strings]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com/?p=2634</guid>
		<description><![CDATA[Working with strings is a very common task for most C# developers. The .NET Framework offers good variety of tools for working with strings, but care must be taken as there are several gotchas to trip up the beginner. The first thing to note about strings in .NET is that they are Reference Types. Reference [...]]]></description>
			<content:encoded><![CDATA[<p>Working with strings is a very common task for most C# developers. The .NET Framework offers good variety of tools for working with strings, but care must be taken as there are several gotchas to trip up the beginner.</p>
<p>The first thing to note about strings in .NET is that they are Reference Types. Reference types are live on the managed heap in .NET and so they are managed by the .NET Garbage Collector and unlike Value types they are not automatically  destroyed when they are out of scope.</p>
<p>Strings can be easily instantiated using the below syntax:</p>
<pre>string s1;</pre>
<p>Note that there is no default value for a string, thus you need to assign a value to the string before attempting to access it:</p>
<pre>string s1;
Literal1.Text = s1; //Will give run-time error 

string s2 = ""; //This is as close as you can get to assigning nothing to a string;
Literal1.Text = s2;</pre>
<p>There are numerous inbuilt methods in the .NET framework for dealing with strings. Namely:</p>
<p>Note that strings are immutable and thus the original string can never be changed. Therefore if you need to alter the string you will need to re-assign it a new string value:</p>
<pre>string s1 = "all lower case";
s1.ToUpper() ; //s1 is unchanged
Literal1.Text = s1;  //outputs 'all lower case' since s1 is unchanged

string s2 = "all lower case";
s2 = s2.ToUpper() ; //s2 is now re-assigned the new uppercase string
Literal2.Text = s2; //outputs 'ALL LOWER CASE'</pre>
<p>For more on string immutability see Strings are Immutable.</p>
<h2>String Concatenation</h2>
<p>C# offers a convenient method for concatenating a string using &#8216;+&#8217; :</p>
<pre>string s1 = "Hong ";
string s2 = "Kong";
Literal1.Text = s1 + s2;</pre>
<p>Whilst this method is convenient it is not efficient for performing a large number of concatenations (since strings are immutable and are refenece types created on the managed heap each concatenation results in the creation of an extra string which is not automatically destroyed and stays in memory until the Garbage Collector destroys it).</p>
<p>To get around this limitation the .NET Framework provides the StringBuilder class which can efficiently concatenate strings using its Append() method:</p>
<pre> StringBuilder sb = new StringBuilder();
 sb.Append("Hong ");
 sb.Append("Kong");

Literal1.Text = sb.ToString();</pre>
<p>This is by way of demonstration since there would not be any memory saving from concatentating two strings (in fact this can consume more memory since the StringBuilder consumes memory). In general concatenating more than four strings is normally when a StringBuilder should be used.</p>
<h2>Escape Characters</h2>
<p>In common with other C-based languages, C# strings may contain escape characters which qualify how the string should be output.<br />
Escape characters begin with a backslash followed by a specific character.</p>
<p>Below are listed the various escape characters and their output:</p>
<p>\&#8217;   Inserts a single quote<br />
\&#8221;    Inserts a double quote<br />
\\    Inserts a backslash<br />
\a    Triggers a system alert<br />
\n    Inserts a new line (on Windows systems)<br />
\r    Inserts a carriage return<br />
\t    Inserts a horizontal tab</p>
<h2>Verbatim Strings</h2>
<p>To preserve a string exactly as it is exactly as it was added simply add the @ character at the start of the string.</p>
<p>For example:</p>
<pre>string outputStr =   "This site is named \'C# Help\'  ";
Response.Write(outputStr);</pre>
<p>This outputs </p>
<pre>This site is named 'C# Help'</pre>
<p>To output the string verbatim add the @ character at the start of the string.</p>
<pre>string outputStr =   @"This site is named \'C# Help\'  ";
Response.Write(outputStr);</pre>
<p>This outputs </p>
<pre>This site is named \'C# Help\'</pre>
<p>Note that this will also preserve white space:</p>
<pre>string outputStr =   @"This is a                  broken
up
             string";  </pre>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2011/06/c-strings-getting-started-with-strings/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# String manipulation, string constructors, string assignment, and the StringBuilder class</title>
		<link>http://www.csharphelp.com/2007/09/c-string-manipulation-string-constructors-string-assignment-and-the-stringbuilder-class/</link>
		<comments>http://www.csharphelp.com/2007/09/c-string-manipulation-string-constructors-string-assignment-and-the-stringbuilder-class/#comments</comments>
		<pubDate>Tue, 25 Sep 2007 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Strings]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=677</guid>
		<description><![CDATA[Why is string manipulation so important?Because, as programmers, we do so much of it. In fact, on some days, itseems that everything is string manipulation. If you know how toprogram with strings, you&#39;re a great way along the journey to becominga powerful programmer. Fortunately, C# provides facilities for workingwith and manipulating strings. In this tutorial [...]]]></description>
			<content:encoded><![CDATA[<p><span class="smallblack">Why is string manipulation so important?Because, as programmers, we do so much of it. In fact, on some days, itseems that everything is string manipulation. If you know how toprogram with strings, you&#39;re a great way along the journey to becominga powerful programmer. Fortunately, C# provides facilities for workingwith and manipulating strings. In this tutorial we will explain thetypes and methods related to strings, so that you can make short workof most common string-manipulation tasks in your projects.</span></p>
<p><span class="smallblack"> This tutorial provides the information you need about:</span></p>
<p>&nbsp;</p>
<ul><span class="smallblack">
<li><a href="http://www.csharphelp.com/archives4/archive702.html#c#strings">Understanding C# Strings</a> </li>
<li><a href="http://www.csharphelp.com/archives4/archive702.html#chartype">Working with the Char Type</a> </li>
<li><a href="http://www.csharphelp.com/archives4/archive702.html#controlchars">Control Characters</a> </li>
<li><a href="http://www.csharphelp.com/archives4/archive702.html#stringassign">String Assignment</a> </li>
<li><a href="http://www.csharphelp.com/archives4/archive702.html#stringconstruct">The String Constructor</a> </li>
<li><a href="http://www.csharphelp.com/archives4/archive702.html#verbatim">Verbatim Strings</a></li>
<li><a href="http://www.csharphelp.com/archives4/archive702.html#instancemethods">Using String Methods</a> </li>
<li><a href="http://www.csharphelp.com/archives4/archive702.html#stringbuilder">Understanding the StringBuilder Class</a> </li>
<p></span></ul>
<p><span class="smallblack"><a name="c#strings"><br />
<h4>Understanding C# Strings</h4>
<p></a>In C#, a text string is stored in a data type named string, which is analias to the System.String type. In other words, when you create astring, you instantiate a System.String object. In addition to itsinstance members, the System.String class has quite a few importantstatic methods. These methods don.t require a string instance to work.It.s important to understand that the string type is immutable. Thismeans that <b>once it has been created, a string cannot be changed</b>. No characters can be added or removed from it, nor can its length be changed. In those situations in which it <i>appears</i> that a string&#39;s contents have been changed, what has really happened is that a new string instance has been created.</span></p>
<p><span class="smallblack">But wait, you say, my strings change all the time when I do things like:</span></p>
<p><span class="smallblack"> </span></p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />string str = &quot;I am having a great deal of fun&quot;;<br />str += &quot; on the DonationCoder website&#8230; &quot;;<br />str += &quot; The End&quot;; <br /></span></span>
<p>&nbsp;</p>
<p><span class="smallblack">Well, my friend, what this set of statements actually does is create a new instance of the variable <b>str</b> each time a value is assigned to <b>str</b>. In other words, in this example, an instance of <b>str</b>has been created and a literal string value assigned to it three times.The statement that the type is immutable means that an instance cannotbe edited but it can be <i>assigned</i>.</span></p>
<p><span class="smallblack">Using an instance method without an assignmentis syntactically legal, but it doesn.t do anything (has no effect). Asa demonstration of my claim that an instance cannot be edited, examinethe following code:</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />using System;</p>
<p>namespace ConsoleApplication1 {<br /> class Program {<br /> static void Main(string[] args) {<br /> string str = &quot;Mouser&quot;;<br /> <span style="background-color:#ffcc00;">str.Replace(&quot;u&quot;, &quot;U&quot;);</span><br /> Console.WriteLine(str);<br /> Console.ReadLine();<br /> }<br /> }<br />}</p>
<p></span></span>
<p><span class="smallblack">The above code does <span style="text-decoration:underline;">not</span> change the contents of the variable <b>str</b>, because an instance cannot be edited. Run the above code in your IDE, and you&#39;ll see this result:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/immutable_instance.png" alt="" /></span></p>
<p><span class="smallblack">However, combining it with an assignment would work:</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />using System;</p>
<p>namespace ConsoleApplication1 {<br /> class Program {<br /> static void Main(string[] args) {<br /> string str = &quot;Mouser&quot;;<br /> <span style="background-color:#ffcc00;">str = str.Replace(&quot;u&quot;, &quot;U&quot;);</span><br /> Console.WriteLine(str);<br /> Console.ReadLine();<br /> }<br /> }<br />}<br /></span></span>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/str_assignment.png" alt="" /></span></p>
<p><span class="smallblack">The value of the newly assigned <b>str</b>instance is, of course, MoUser. If you carefully compare the two sourcecode listings above, you&#39;ll see that the only difference occurs in thetwo highlighted lines. The second source code listing differs only byprefacing that line of code with <b>str =</b>, which tells the compiler to assign whatever follows the equal sign to the <b>str</b> instance of the String type. You may remember, from a previous tutorial in this series, that a <b>type</b> is defined by a class. There is, indeed, a String class. So, when I write <b><span style="color:blue;">string</span> str = &quot;Bryan&quot;;</b>, what I&#39;ve really done is created an instance of the String class called <b>str</b>, then assigned the text <i>Bryan</i> to it.</span></p>
<p><span class="smallblack">Is there any real problem with this use ofassignment in conjunction with strings? Well, no, it.s easy enough touse assignments when you need to change the value of a string variable.But instantiating and destroying strings every time you need to changeor edit one has negative performance consequences. If performance is anissue, you should consider working with instances of theSystem.Text.StringBuilder class, which are mutable (can be changed).The StringBuilder class is discussed later in this tutorial in a littlemore detail.</span></p>
<p><span class="smallblack">Once created, a string has a specific length.which, of course, is fixed (since the <span style="color:blue;">string</span>type is immutable). Unlike in the C language, in which a string issimply an array of characters terminated with a zero byte, a C# stringis <i>not</i> a terminated array of characters. So, how does onedetermine the length of a C# string? As you probably know, you canquery the read-only <b>Length</b> property of the string instance tofind its length. Let&#39;s write a short console program demonstrating theuse of this property:</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />using System;</p>
<p>namespace ConsoleApplication1 {<br /> class Program {<br /> static void Main(string[] args) {<br /> string name = string.Empty;<br /> do {<br /> Console.Write(&quot;Please enter a name (enter &quot;quit&quot; to exit program): &quot;);<br /> name = Console.ReadLine();<br /> if (name.Trim().ToLower() != &quot;quit&quot;) {<br /> Console.WriteLine(&quot;&quot;{0}&quot;, is {1} characters in length.n&quot;, name, name.Length);<br /> }<br /> } while (name.Trim().ToLower() != &quot;quit&quot;);<br /> }<br /> }<br />}<br /></span></span>
<p><span class="smallblack">Now click on <a href="http://www.csharphelp.com/archives4/namelength.htm" target="_blank">this</a> link to see the program in action. </span></p>
<hr />
<p><span class="smallblack"><a name="chartype"><br />
<h4>Working with the Char type</h4>
<p></a>Char is a value type that contains a single Unicode character. Whilechars have a numeric value from hexadecimal 0&#215;0000 through 0xFFFF, theyare not directly numerically usable without explicit type casting.</span></p>
<p><span class="smallblack">Literal values are assigned to char variablesusing singl<br />
e quotes<br />
. The literal can be a simple, single letter, or anescape sequence (for more on escape sequences, see the next section).Here are two examples:</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />char chr = &#39;P&#39;; // contains capital P<br />char pi = &#39;u03A0.; // contains capital Pi <br /></span></span>
<p><span class="smallblack">The <span style="color:blue;">char</span> data type is related to the <span style="color:blue;">string</span>data type: A string can be constructed from (or converted into) anarray of characters but string and char are two distinct types.</span></p>
<p><span class="smallblack">Suppose you have a string defined like this:</span></p>
<p><span class="smallblack"><b><span style="color:blue;">string</span> str = &quot;rotfl&quot;;</b></span></p>
<p><span class="smallblack">You can retrieve a character of the string using the string.s indexer. For example, the following statement</span></p>
<p><span class="smallblack"><b><span style="color:blue;">char</span> chr = str[1];</b></span></p>
<p><span class="smallblack">stores the character .o. in the variable <b>chr</b>. But you cannot set a character in the string with a statement like <b>str[1] = &#39;a&#39;;</b>because the indexer property of the String class is read-only.(Actually, one would expect this in any case, because the stringinstance is immutable.) </span></p>
<p><span class="smallblack">If you use the Object Browser to have a look at the String class, you.ll see that its indexer property, declared as <b>this[int]</b>, has a get accessor, but no set accessor.</span></p>
<p><span class="smallblack"> </span></p>
<p><span class="smallblack"><br /></span></p>
<hr />
<p><span class="smallblack"><br /><a name="controlchars"><br />
<h4>Control Characters</h4>
<p></a> The backslash() is a special control character, also called the escape character.The character after the backslash has a special significance. See thefollowing table for the meaning of each escape sequence:</span></p>
<p>
<table class="MsoNormalTable" style="margin-left:54.9pt;border-collapse:collapse;" border="2" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td style="padding:0in 5.4pt;width:82.35pt;" valign="top" width="110">
<p class="TableHead"><span style="text-transform:uppercase;">Character&lt;o:p&gt;&lt;/o:p&gt;</span></p>
</td>
<td style="padding:0in 5.4pt;width:363.15pt;" valign="top" width="484">
<p class="TableHead"><span style="text-transform:uppercase;">Meaning&lt;o:p&gt;&lt;/o:p&gt;</span></p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:82.35pt;" valign="top" width="110">
<p class="TableEntry"><span class="InlineCode"><span> &lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:363.15pt;" valign="top" width="484">
<p class="TableEntry">Null&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:82.35pt;" valign="top" width="110">
<p class="TableEntry"><span class="InlineCode"><span>b&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:363.15pt;" valign="top" width="484">
<p class="TableEntry">Backspace&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:82.35pt;" valign="top" width="110">
<p class="TableEntry"><span class="InlineCode"><span>t&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:363.15pt;" valign="top" width="484">
<p class="TableEntry">Tab&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:82.35pt;" valign="top" width="110">
<p class="TableEntry"><span class="InlineCode"><span>r&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:363.15pt;" valign="top" width="484">
<p class="TableEntry">Carriage return&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:82.35pt;" valign="top" width="110">
<p class="TableEntry"><span class="InlineCode"><span>n&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:363.15pt;" valign="top" width="484">
<p class="TableEntry">New line&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:82.35pt;" valign="top" width="110">
<p class="TableEntry"><span class="InlineCode"><span>v&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:363.15pt;" valign="top" width="484">
<p class="TableEntry">Vertical tab&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:82.35pt;" valign="top" width="110">
<p class="TableEntry"><span class="InlineCode"><span>f&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:363.15pt;" valign="top" width="484">
<p class="TableEntry">Form feed&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:82.35pt;" valign="top" width="110">
<p class="TableEntry"><span class="InlineCode"><span>u</span></span>, <span class="InlineCode"><span>x&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:363.15pt;" valign="top" width="484">
<p class="TableEntry">A single Unicode character when followed by a four-digit hexadecimal number&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:82.35pt;" valign="top" width="110">
<p class="TableEntry"><span class="InlineCode"><span>&quot;&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:363.15pt;" valign="top" width="484">
<p class="TableEntry">Double quote&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:82.35pt;" valign="top" width="110">
<p class="TableEntry"><span class="InlineCode"><span>&#39;&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:363.15pt;" valign="top" width="484">
<p class="TableEntry">Single quote&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:82.35pt;" valign="top" width="110">
<p class="TableEntry"><span class="InlineCode"><span>&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:363.15pt;" valign="top" width="484">
<p class="TableEntry">Backslash&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
</tbody>
</table>
<p><span class="smallblack">Here is a very brief program that demonstrates use of the backspace escape character:</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />using System;</p>
<p>class Program{</p>
<p> static void Main(){</p>
<p>	Console.Write(&quot;This is line #1<span style="background-color:#ffcc00;">bb</span>&quot;);<br /> Console.Write(&quot;number 2&quot;);<br /> Console.ReadLine();</p>
<p> }//end Main</p>
<p>}//end class Program</p>
<p></span></span>
<p><span class="smallblack">The program&#39;s output looks like this:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/backspace.png" alt="" /></span></p>
<p><span class="smallblack">As you can see, there are two backspace escape characters at the end of the first <span style="font-family:FixedSys;">Console.Write()</span>parameter. I&#39;ve highlighted these in the source code listing above.These have the effect of backing the cursor up to just in front of the <b>#</b> symbol. The subsequent <span style="font-family:Fixedsys;">Console.Write()</span> invocation then prints &quot;number 2&quot;, <i>starting</i> at the position occupied by the <b>#</b> symbol, and thus effectively overwriting <b>#1</b>.</span></p>
<p><span class="smallblack">The escape sequences u or x are used(interchangeably) to specify a single Unicode character. For example,x03A9 and u03A9 both mean the Greek letter capital omega. The escapesequences x03A3 and u03A3 will appear as the Greek letter capitalsigma:</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />using System;</p>
<p>class Program{</p>
<p> static void Main(){</p>
<p> Console.Write(&quot;This is Omega: {0}. And this is Sigma: {1} &quot;,<br /> &quot;u03A9&quot;, &quot;u03A3&quot;);</p>
<p> Console.ReadLine();</p>
<p> }//end Main</p>
<p>}//end class Program</p>
<p></span></span>
<p><span class="smallblack">The output from the above program is:</span></p>
<p><span cl</p>
<p>ass="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/omegasigma.png" alt="" /></span></p>
<p><span class="smallblack">A complete listing of unicode character sets can be found at <a href="http://www.unicode.org/charts/" target="_blank">http://www.unicode.org/charts/</a>.</span></p>
<p><span class="smallblack"><br /></span></p>
<hr />
<p><span class="smallblack"><br /><a name="stringassign"><br />
<h4>String Assignment</h4>
<p></a>There are different ways to create strings in C#. You can, forinstance, declare a string variable, without initializing it, such asin this example:</span></p>
<p><span class="smallblack"><b><span style="color:blue;">string</span> mystring;</b></span></p>
<p><span class="smallblack">While this is legal, we&#39;ve also discussed thefact that attempting to use an uninitialized string variable causes acompiler error. For this reason, it&#39;s generally a good idea toinitialize a string variable when you declare it:</span></p>
<p><span class="smallblack"><b><span style="color:blue;">string</span> mystring = &quot;Hello, world!&quot;;</b></span></p>
<p><span class="smallblack">Because a string variable is a reference type, it can be initialized to <b>null</b>:</span></p>
<p><span class="smallblack"><b><span style="color:blue;">string</span> mystring = null;</b></span></p>
<p><span class="smallblack">And initializing a string to <b>null</b> is <span style="text-decoration:underline;">not</span> the same thing as initializing it to an empty string. The above is not equivalent to this:</span></p>
<p><span class="smallblack"><b><span style="color:blue;">string</span> mystring = string.Empty;</b></span></p>
<p><span class="smallblack">In the case of the null assignment, no memoryhas been allocated for the string. An attempt to determine the lengthof a null string by using its <b>Length</b> property causes anexception to be thrown. For an example of this, see the followingprogram listing, and then the output it produces. The program willcompile okay, because there is no syntax error. However, attempting toexecute the highlighted line causes a runtime error:</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />using System;</p>
<p>class Program{</p>
<p> static void Main(){</p>
<p> string mystring = null;<br /> <span style="background-color:#ffcc00;">Console.WriteLine(&quot;Length of mystring is {0}&quot;, mystring.Length);</span><br /> Console.ReadLine();</p>
<p> }//end Main</p>
<p>}//end class Program</p>
<p></span></span>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/nulllength.png" alt="" /></span></p>
<p><span class="smallblack"><br />The <b>Length</b> property of an empty string is 0.The preferred way to initialize an empty string is to use the static Empty field of the String class: <b><span style="color:blue;">string</span> str = string.Empty;</b></span></p>
<p><span class="smallblack">However, you will sometimes see it done thusly: <b><span style="color:blue;">string</span> str = &quot;&quot;;</b></span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><br /></span></p>
<hr />
<p><span class="smallblack"><br /><a name="stringconstruct"><br />
<h4>The String Constructor</h4>
<p></a>The String class itself has eight constructors. If you look in theObject Browser, you can see that five of these use pointers and are notsafe under the rules of the Common Language Specification (CLS) that.NET languages must follow. We will only discuss the other threeconstructors.</span></p>
<p><span class="smallblack">You may recall from a previous tutorial thatwhen a method has more than one form, via differing method signatures,it is said to be <i>overloaded</i>. You also learned in a previoustutorial that a constructor is a special class method that, if present,is invoked whenever a new instance of that class is created. Well, theString class has several overloaded constructors.</span></p>
<p><span class="smallblack">The first such overloaded constructor thatwe&#39;ll discuss takes two parameters &#8212; a character and an integer. Itthen produces a string of that particular character that is xcharacters in length, where x is the value of the integer passed as theconstructor&#39;s second argument. This constructor takes the followingform:</span></p>
<p><span class="smallblack"><span style="font-family:Fixedsys;">String(char, int)</span></span></p>
<p><span class="smallblack">For example, the following lines of code, placed inside the Main method of a Console C# application&#8230;</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />string s = new string(&#39;a&#39;,5);<br />Console.WriteLine(s);<br />Console.ReadLine();<br /></span></span>
<p><span class="smallblack"> &#8230;would produce the following output:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/strconstruct1.png" alt="" /></span></p>
<p><span class="smallblack">The next overloaded string constructor we&#39;ll consider takes the following form:</span></p>
<p><span class="smallblack"><span style="font-family:Fixedsys;">String(char[])</span></span></p>
<p><span class="smallblack">This constructor takes a character array as aparameter, and converts the character array into a string. For example,the following code&#8230;</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />using System;</p>
<p>class Program{</p>
<p> static void Main(){</p>
<p> char[] mychararray = new char[5]{&#39;B&#39;,&#39;r&#39;,&#39;y&#39;,&#39;a&#39;,&#39;n&#39;};<br /> string mystring = new string(mychararray);<br /> Console.WriteLine(&quot;The 5-element character array has been converted into this string: &quot;{0}&quot;.&quot;, mystring);<br /> Console.ReadLine();</p>
<p> }//end Main</p>
<p>}//end class Program</p>
<p></span></span>
<p><span class="smallblack">&#8230;produces this output&#8230;</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/strconstruct3.png" alt="" /></span></p>
<p><span class="smallblack">The final overloaded string constructor we&#39;llconsider is simply an extension of the constructor we just examined,and takes this form:</span></p>
<p><span class="smallblack"><span style="font-family:Fixedsys;">String(char[],int,int)</span></span></p>
<p><span class="smallblack">Like the previous constructor, it converts acharacter array into a string, but it additionally will then derive astring with a particular starting and stopping position within theconverted string. For example, if these lines were put into a consoleprogram&#8230;</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />char[] mychararray = new char[11]{&#39;N&#39;,&#39;e&#39;,&#39;w&#39;,&#39;Y&#39;,&#39;o&#39;,&#39;r&#39;,&#39;k&#39;,&#39;C&#39;,&#39;i&#39;,&#39;t&#39;,&#39;y&#39;};<br />string mystring = new string(mychararray,3,6);<br />Console.WriteLine(mystring);<br /></span></span>
<p><span class="smallblack">&#8230;the output would be <i>York</i>.</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><br /></span></p>
<hr />
<p><span class="smallblack"><br /><a name="verbatim"><br />
<h4>Verbatim Strings</h4>
<p></a> You could use the <b>@</b>symbol to use a keyword as an identifier if you were so inclined. Youcould create variables named, for example, @if, @string, and @true;but, just because one <span style="text-decoration:underline;">can</span> do something, doesn.t mean it is a good idea.</span></p>
<p><span class="smallblack">In the context of strings, the @ symbol isused to create verbatim string literals. The @ symbol tells the stringconstructor to use the string literal that follows it literally even ifit includes escape characters or spans multiple lines.</span></p>
<p><span class="smallblack">This comes in handy when working withdirectory paths (without the @, you would have to double eachbackslash). For example, the following two strings are equivalent:</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />string desktop = &quot;C:Documents and SettingsOwnerDesktop&quot;; //uses eight slashes<br />stri</p>
<p>ng desktop = @&quot;C:Documents and SettingsOwnerDesktop&quot;; //uses four slashes<br /></span></span>
<p><span class="smallblack">You can also use the ampersand symbol to causea single string to span more than one line. For example, consider thefollowing program listing, and the output it produces:</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />using System;</p>
<p>class Program {</p>
<p> static void Main() {</p>
<p> string str =<br /> @&quot;I&#39;m so happy to be a string<br /> that is split across<br /> a number of different<br /> lines.&quot;;</p>
<p> Console.WriteLine(str);<br /> Console.ReadLine();<br /> }<br />}<br /></span></span>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/multilinestring.png" alt="" /></span></p>
<p><span class="smallblack">In console mode, line breaks are preserved. Ina WinForms application (we&#39;ll learn how to code those in latertutorials), you could assign <b>str</b> to a textbox control that hasits multiline property set to true, and all line breaks and whitespacewould be faithfully preserved.</span></p>
<p><span class="smallblack"><br /></span></p>
<hr />
<p><span class="smallblack"><br /><a name="instancemethods"><br />
<h4>Using String Methods</h4>
<p></a> The Stringclass provides many powerful instance and static methods. These methodsare described in this section. Most of these methods are overloaded, sothere are multiple ways that each can be used. The table belowdescribes many of the instance methods of the String class.</span></p>
<p>
<table border="2" cellpadding="2" cellspacing="2" width="70%">
<tbody>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableHead"><span style="text-transform:uppercase;">Method&lt;o:p&gt;&lt;/o:p&gt;</span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableHead"><span style="text-transform:uppercase;">What It Does&lt;o:p&gt;&lt;/o:p&gt;</span></p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>Clone&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Returns a reference to the instance of the string.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>CompareTo&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Compares this string with another.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>CopyTo&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Copies the specified number of characters from the string instance to a char array.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>EndsWith&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Returns true if the specified string matches the end of the instance string.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>Equals&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Determines whether the instance string and a specified string have the same value.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>GetEnumerator&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Method required to support the <span class="InlineCode"><span>IEnumerator</span></span> interface.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>IndexOf&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Reports the index of the first occurrence of a specified character or string within the instance.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>Insert&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Returns a new string with the specified string inserted at the specified position in the current string.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>LastIndexOf&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Reports the index of the last occurrence of a specified character or string within the instance.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>PadLeft&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Returns a new string with the characters in this instance right-aligned by padding on the left with spaces or a specified character for a specified total length.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>PadRight&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Returns a new string with the characters in this instance left-aligned by padding on the right with spaces or a specified character for a specified total length.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>Remove&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Returns a new string that deletes a specified number of characters from the current instance beginning at a specified position.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>Replace&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Returns a new string that replaces all occurrences of a specified character or string in the current instance, with another character or string.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry">&lt;st1:city&gt;&lt;st1:place&gt;<span class="InlineCode"><span>Split</span></span>&lt;/st1:place&gt;&lt;/st1:city&gt;<span class="InlineCode"><span>&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Identifies the substrings in this instance that are delimited by one or more characters specified in an array, then places the substrings into a string array.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>StartsWith&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;w</p>
<p>idth:339.55pt;" valign="top" width="453">
<p class="TableEntry">Returns <span class="InlineCode"><span>true</span></span> if the specified string matches the beginning of the instance string.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>Substring&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Returns a substring from the instance.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>ToCharArray&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Copies the characters in the instance to a character array.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>ToLower&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Returns a copy of the instance in lowercase.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>ToUpper&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Returns a copy of the instance in uppercase.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>Trim&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Returns a copy of the instance with all occurrences of a set of specified characters from the beginning and end removed.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>TrimEnd&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Returns a copy of the instance with all occurrences of a set of specified characters at the end removed.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:103.25pt;" valign="top" width="138">
<p class="TableEntry"><span class="InlineCode"><span>TrimStart&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:339.55pt;" valign="top" width="453">
<p class="TableEntry">Returns a copy of the instance with all occurrences of a set of specified characters from the beginning removed.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
</tbody>
</table>
<p><span class="smallblack">Whereas the above table shows many of the String class <i>instance</i> methods, the following tables shows some of the <i>static</i> methods of the String class.</span></p>
<p>
<table border="2" cellpadding="2" cellspacing="2" width="70%">
<tbody>
<tr>
<td style="padding:0in 5.4pt;width:109.85pt;" valign="top" width="146">
<p class="TableHead"><span style="text-transform:uppercase;">Method&lt;o:p&gt;&lt;/o:p&gt;</span></p>
</td>
<td style="padding:0in 5.4pt;width:332.95pt;" valign="top" width="444">
<p class="TableHead"><span style="text-transform:uppercase;">What It Does&lt;o:p&gt;&lt;/o:p&gt;</span></p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:109.85pt;" valign="top" width="146">
<p class="TableEntry"><span class="InlineCode"><span>Compare&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:332.95pt;" valign="top" width="444">
<p class="TableEntry">Compares two string objects.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:109.85pt;" valign="top" width="146">
<p class="TableEntry"><span class="InlineCode"><span>CompareOrdinal&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:332.95pt;" valign="top" width="444">
<p class="TableEntry">Compares two string objects without considering the local national language or culture.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:109.85pt;" valign="top" width="146">
<p class="TableEntry"><span class="InlineCode"><span>Concat&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:332.95pt;" valign="top" width="444">
<p class="TableEntry">Creates a new string by concatenating one or more strings.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:109.85pt;" valign="top" width="146">
<p class="TableEntry"><span class="InlineCode"><span>Copy&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:332.95pt;" valign="top" width="444">
<p class="TableEntry">Creates a new instance of a string by copying an existing instance.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:109.85pt;" valign="top" width="146">
<p class="TableEntry"><span class="InlineCode"><span>Format&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:332.95pt;" valign="top" width="444">
<p class="TableEntry">Formats a string using a format specification. See Formatting Overview in online help for more information about format specifications.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
<tr>
<td style="padding:0in 5.4pt;width:109.85pt;" valign="top" width="146">
<p class="TableEntry"><span class="InlineCode"><span>Join&lt;o:p&gt;&lt;/o:p&gt;</span></span></p>
</td>
<td style="padding:0in 5.4pt;width:332.95pt;" valign="top" width="444">
<p class="TableEntry">Concatenates a specified string between each element in a string to yield a single concatenated string.&lt;o:p&gt;&lt;/o:p&gt;</p>
</td>
</tr>
</tbody>
</table>
<p><span class="smallblack">Here is a program that demonstrates the use of <span style="font-family:Fixedsys;">String.Clone()</span>.What this program shows is that cloning a string returns a reference tothat string instance, which can be assigned to another string variable,giving that other string variable a reference to the exact samelocation in memory. In other words, both strings will reference thesame instance, after cloning has occurred.</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />using System;</p>
<p>class Program {</p>
<p> static void Main() {</p>
<p> bool test = false;</p>
<p> string s1 = &quot;William&quot;;<br /> string s2 = &quot;Bryan&quot;;<br /> string s3 = &quot;Miller&quot;;</p>
<p> Console.WriteLine(&quot;s1 = {0}, s2 = {1}, s3 = {2}n&quot;, s1, s2, s3);</p>
<p> s2 = (string)s1.Clone(); //now s2 references the same string instance that s1 does<br /> Console.WriteLine(&quot;s2 = (string)s1.Clone(); //now s2 references the same string instance that s1 doesn&quot;);</p>
<p> test = SameValue(s1, s2);</p>
<p> if (test) {<br /> Console.WriteLine(&quot;s2 now holds the same value that s1 holds, i.e., &quot;{0}&quot;n&quot;, s1);<br /> }</p>
<p> test = ReferencesSameObject(s1, s2);</p>
<p> if (test) {<br /> Console.WriteLine(&quot;s1 and s2 reference the same instance object.n&quot;);<br /> }</p>
<p> s2 = s3;</p>
<p> Console.WriteLine(&quot;s2 = s3; // now s2 = {0} and s3 = {1}n&quot;, s2, s3);</p>
<p> test = SameValue(s2, s3);</p>
<p> if (test) {<br /> Console.WriteLine(&quot;s2 and s3 now hold the same valuen&quot;);<br /> }</p>
<p> test = ReferencesSameObject(s2, s3);</p>
<p> if (test) {<br /> Console.WriteLine(&quot;s2 and s3 now reference the very same instance.&quot;);<br /> } else {<br /> Console.WriteLine(&quot;s2 and s3 do NOT reference the same instance.&quot;);<br /> }</p>
<p> Console.ReadLine();</p>
<p> }//end Main</p>
<p> private static bool SameValue(object o1, object o2){<br /> if (o1.Equals(o2)) {<br /> return true;<br /> } else {<br /> return false;<br /> }<br /> }</p>
<p> private static bool ReferencesSameObject(object o1, object o2) {<br</p>
<p> /> if (Object.ReferenceEquals(o1, o2)) {<br /> return true;<br /> } else {<br /> return false;<br /> }<br /> }<br />}<br /></span></span>
<p><span class="smallblack">Here is the output the above program produces:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/stringclone.png" alt="" /></span></p>
<p><span class="smallblack">Whereas the <span style="font-family:Fixedsys;">Clone()</span> method of the String object returns a reference to the string instance, the static <span style="font-family:Fixedsys;">Copy()</span> method creates a new instance of a string by copying an existing instance, as the following program demonstrates:</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />// Sample for String.Copy()<br />using System;</p>
<p>class Sample {<br /> public static void Main() {<br /> string str1 = &quot;abc&quot;;<br /> string str2 = &quot;xyz&quot;;<br /> Console.WriteLine(&quot;1) str1 = &#39;{0}&#39;&quot;, str1);<br /> Console.WriteLine(&quot;2) str2 = &#39;{0}&#39;&quot;, str2);<br /> Console.WriteLine(&quot;Copy&#8230;&quot;);<br /> str2 = String.Copy(str1);<br /> Console.WriteLine(&quot;3) str1 = &#39;{0}&#39;&quot;, str1);<br /> Console.WriteLine(&quot;4) str2 = &#39;{0}&#39;&quot;, str2);<br /> }<br />}<br />/*<br />This example produces the following results:<br />1) str1 = &#39;abc&#39;<br />2) str2 = &#39;xyz&#39;<br />Copy&#8230;<br />3) str1 = &#39;abc&#39;<br />4) str2 = &#39;abc&#39;<br />*/</p>
<p></span></span>
<p><span class="smallblack">Next we have the <span style="font-family:Fixedsys;">CompareTo()</span>method. This method returns an integer whose value signals how the twostrings compare. First, I&#39;ll show you code that will throw anexception. The comment in the following program listing explains whatthe problem is that leads to an exception being thrown.</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />using System;</p>
<p>public class Program {<br /> public static void Main() {</p>
<p> MyClass my = new MyClass();</p>
<p> string s = &quot;sometext&quot;;</p>
<p> try {<br /> int i = s.CompareTo(my); //comparing string <b>s</b> to class instance <b>my</b> (which doesn&#39;t evaluate to a string)<br /> } catch (Exception e) {<br /> Console.WriteLine(&quot;Error: {0}&quot;, e.ToString());<br /> }</p>
<p> Console.ReadLine();<br /> }<br />}</p>
<p>public class MyClass { }</p>
<p></span></span>
<p><span class="smallblack">Now, unlike the above program, whichdemonstrates the throwing of an exception due to an invalid parameter,let&#39;s see a program that demonstrates the other three cases we mightencounter when dealing with the <span style="font-family:Fixedsys;">CompareTo()</span> instance method:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/stringcompareto.png" alt="" /></span></p>
<p><span class="smallblack">If you wish to view the source code that produces the output shown above, click <a href="http://www.csharphelp.com/archives4/sample_code/cs7_srccode_listings.htm#stringcompareto_cs" target="_blank">here</a>.</span></p>
<p><span class="smallblack">The example program <a href="http://www.csharphelp.com/archives4/sample_code/cs7_srccode_listings.htm#stringcopyto_cs" target="_blank">here</a> produces this output:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/stringcopyto.png" alt="" /></span></p>
<p><span class="smallblack">A fairly straightforward instance method of the String class is the <span style="font-family:Fixedsys;">EndsWith()</span> method. It is used to determine if a specified string matches the end of an instance string. Consider <a href="http://www.csharphelp.com/archives4/sample_code/cs7_srccode_listings.htm#stringendswith_cs" target="_blank">this</a> program listing, and the output it creates (shown below):</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/stringendswith.png" alt="" /></span></p>
<p><span class="smallblack">Now, the above program uses a couple of thingswe have not covered yet in any of our tutorials &#8212; the foreach loop,and arrays. For now, don&#39;t worry about those. The lines of code thatare important in this example are these lines, which allow the programto determine how many Millers and Pikes are in the names array:</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />if(name.EndsWith(&quot;Miller&quot;)){<br /> m++;<br />}</p>
<p>if(name.EndsWith(&quot;Pike&quot;)){<br /> p++;<br />}<br /></span></span>
<p><span class="smallblack">The integer variables <b>m</b> and <b>p</b>permit us to track how many Millers and Pikes we come across as wetraverse the entire string array of names. By incrementing one or theother of these values when we encounter the corresponding surname inour array, we end up, after finishing stepping through each member ofthe array, having an accurate count of the number of incidents of eachsurname.</span></p>
<p><span class="smallblack">The next String instance method we&#39;ll demonstrate is the <span style="font-family:Fixedsys;">String.Equals()</span>method, which simply determines if the instance string and anotherstring have the same value. An example program can be found <a href="http://www.csharphelp.com/archives4/sample_code/cs7_srccode_listings.htm#stringequals_cs" target="_blank">here</a>.I&#39;ll not dwell on this particular method, because its usage is fairlyobvious, and I think the example program succinctly demonstrates this.</span></p>
<p><span class="smallblack"> Now we come to the <span style="font-family:Fixedsys;">String.GetEnumerator()</span>method, which is included in order for programming languages thatsupport the IEnumerator interface to iterate through members of acollection. For example, the Microsoft Visual Basic and C# programminglanguages&#39; <b>foreach</b> statement invokes this method to return a <b>CharEnumerator</b>object that can provide read-only access to the characters in a givenstring instance. This is not a method you&#39;ll need in your day to dayprogramming tasks.</span></p>
<p><span class="smallblack">Moving on, we come to the <span style="font-family:Fixedsys;">String.IndexOf()</span>method, which reports the index of the first occurrence of a specifiedcharacter or string within the instance. Remembering that the firstposition in a string is position 0, what value do you think <b>i</b> holds below?</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />string s = &quot;abcde&quot;;<br />int i = s.IndexOf(&quot;b&quot;);<br /></span></span>
<p><span class="smallblack">If you said &quot;i = 1&quot;, you are correct! How about character <i>e</i>? Position 4, right!</span></p>
<p><span class="smallblack">It is worth noting that this method can beuseful whenever you want to determine if a string contains a particularcharacter or substring. The integer value returned by this method, ifthe specified character or string is <span style="text-decoration:underline;">not</span> found, is negative one, i.e., -1. This can come in handy in any number of common programming tasks.</span></p>
<p><span class="smallblack">Another very handy instance method of the String object is <span style="font-family:Fixedsys;">String.Substring()</span>instance method, which returns a substring (i.e., a string that lieswithin the string) from the instance string, by acting upon two integervalues you pass the method as arguments for its parameters. The formthat this method takes is <span style="font-family:Fixedsys;">String.Substring(start, length)</span>, where <b>start</b> is the position within the string where the substring starts, and <b>length</b> is the number of characters, beginning with the character found at position <b>start</b>, that the substring holds.</span></p>
<p><span class="smallblack">Perhaps an example will help. Let&#39;s take the word <i>internet</i>. To extract the string <i>net</i> from it, we&#39;d have something like this:</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"> <br />string s = &quot;internet&quot;;<br />string t = s.Substring(5,3);<br /></span></span>
<p><span class="smallblack">The <span style="font-family:Fixedsys;">String.Insert()</span>method returns a new string with a specified string of charactersinserted into the instance string at the specified position. Forexample, let&#39;s say we have a string holding a first name and a lastname, and we want to insert a nickname, in quotation marks, in betweenthe two:</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br /> string s = &quot;Josh Reichler&quot;;<br /> Console.WriteLine(&quot;Example #1:nn&quot; + s);<br /> Console.WriteLine();<br /> Console.WriteLine(&quot;after insertion&#8230;n&quot;);<br /> string t = &quot;Mouser &quot;;<br /> s = s.Insert(5, t);<br /> Console.WriteLine(s);<br /> Console.WriteLine(&quot;nExample #2:n&quot;);<br /> s = &quot;abcefg&quot;;<br /> Console.WriteLine(s + &quot; //missing letter dn&quot;);<br /> Console.WriteLine(&quot;after insertion&#8230;n&quot;);<br /> t = &quot;d&quot;;<br /> s = s.Insert(3, t);<br /> Console.WriteLine(s);<br /> Console.ReadLine();<br /></span></span>
<p><span class="smallblack">The code shown above will produce this output:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/stringinsert.png" alt="" /></span></p>
<p><span class="smallblack">The <span style="font-family:Fixedsys;">String.LastIndexOf()</span> method is rather intutive, and a brief example should serve to demonstrate it adequately:</span></p>
<p><span class="smallblack"><a href="http://www.csharphelp.com/archives4/sample_code/cs7_srccode_listings.htm#stringlastindexof_cs" target="_blank">This</a> program will produce the following output:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/stringlastindexof.png" alt="" /></span></p>
<p><span class="smallblack">The <span style="font-family:Fixedsys;">String.PadLeft()</span>method returns a new string with the characters in this instanceright-aligned by padding on the left with spaces or a specifiedcharacter for a specified total length. In <a href="http://www.csharphelp.com/archives4/sample_code/cs7_srccode_listings.htm#stringpadleft_cs" target="_blank">this</a>program, whose output is shown below, I use this method to align thedecimals in multiple numbers, before adding them together:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/stringpadleft.png" alt="" /></span></p>
<p><span class="smallblack">I think that by now you should be becomingfamiliar with the concept of a string&#39;s Indexer, and the many waysthese string methods take advantage of it to give us usefulfunctionality. PadRight is simply the symmetrical analogue of PadLeft,if you understand EndsWith you can certainly comprehend StartsWith, andwe&#39;ve been using Trim() frequently in our example programs, so youshould be able to understand TrimEnd and TrimStart with ease.</span></p>
<p><span class="smallblack">Let&#39;s examine <span style="font-family:Fixedsys;">String.Split()</span>.This is a very useful method that programmers find applicable to manysituations. As an example, let&#39;s take a sentence, and use this methodto split it up into its constituent words. <a href="http://www.csharphelp.com/archives4/sample_code/cs7_srccode_listings.htm#stringsplit_cs" target="_blank">This</a> program will produce the following output:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/stringsplit.png" alt="" /></span></p>
<p><span class="smallblack">Whereas the <span style="font-family:Fixedsys;">String.Split()</span> method splits a string into an array of strings, based upon a specified character delimiter, the <span style="font-family:Fixedsys;">String.Join()</span> static method takes a string array, and joins its members together into one string, using a specified character delimeter. <a href="http://www.csharphelp.com/archives4/sample_code/cs7_srccode_listings.htm#stringjoin_cs" target="_blank">This</a> program demonstrates this in action.</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><br /></span></p>
<hr />
<p><span class="smallblack"><br /><a name="stringbuilder"><br />
<h4>Understanding the StringBuilder class</h4>
<p></a>As I mentioned earlier in this tutorial, instances of the StringBuilderclass.as opposed to the String class.are mutable, or dynamicallychangeable. StringBuilder is located in the System.Text namespace. Itdoes not have nearly as many members as the String class.but it doeshave enough to get most jobs done. If you have a situation in which youneed to perform many string operations.for example, within a largeloop.from a performance viewpoint it probably makes sense to useStringBuilder instances instead of String instances.In many ways the StringBuilder behaves like a String. But forstring-processing intensive applications, StringBuilder is the betterchoice because its mutability means not nearly so many instances needto be created.</span></p>
<p><span class="smallblack"><a href="http://www.csharphelp.com/archives4/sample_code/cs7_srccode_listings.htm#stringbuilder_cs" target="_blank">This</a>program shows one example of the StringBuilder class in action. I leaveit to you to explore the StringBuilder further, on your own.</span></p>
<p><span class="smallblack"><br /></span></p>
<hr />
<hr />
<p><span class="smallblack"><br />Okay, that&#39;s enough teaching for this tutorial. Now let&#39;s finish up with a programming exercise:</span></p>
<p><span class="smallblack"><br /><span style="background-color:#ffcc00;"><b>Programming Assignment</b>:create a C# console application that prompts the user repeatedly for acharacter. The user can enter whole words, but the program will pullthe first character from the entry and will concatenate it onto <span style="color:blue;">string</span> <b>mystring</b>.Whenever the user enters the word &quot;quit&quot;, the program will stopprompting for characters, and will display the string that has beenconcatenated from the individual characters which the user has entered.</span></span></p>
<p><span class="smallblack"> Sample output:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/strconstruct2.png" alt="" /></span></p>
<p><span class="smallblack">To view my source code for this program, click <a href="http://www.csharphelp.com/archives4/sample_code/cs7_srccode_listings.htm#strconstructor2_cs" target="_blank">here</a>.</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><br /></span></p>
<hr />
<p><span class="smallblack"><br /><span style="background-color:#ffcc00;"><b>Programming Assignment</b>:create a C# console application that finds the very first occurence ofa vowel in a word entered by the user. The program should only allowthe user to enter three to fifteen characters when prompted for a word.If the user enters a string outside this range, the program shouldobject testily, remind the user of the appropriate range for wordlength, then again prompt for a word. When the user has entered a wordwhose length falls in the acceptable range, the program should locatethe very first occurrence of a vowel in that word, counting left toright, and should tell the user what position (start counting at zero)the character occupies in the word (The very first letter in a word isin position zero, and is the 1st character. The second letter is inposition one, and is the 2nd character, and so on). Continue to promptthe user for words until the user enters the word &quot;quit&quot;, which signalsthe program that the user wishes to exit.</span></span></p>
<p><span class="smallblack"> Sample output:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive702/firstvowel.png" alt="" /></span></p>
<p><span class="smallblack">To view my source code for this program, click <a href="http://www.csharphelp.com/archives4/files/archive702/firstvowel.cs" target="_blank">here</a>.</span></p>
<p><span class="smallblack"></p>
<p>Well, I hope that you&#39;ve benefited, at least a little, from this tutorial. As ever, I welcome any <a href="mailto:kyrathaba@yahoo.com?subject=email%20link%20in%20kyrathaba_cs7.htm%20tutorial">feedback</a> you may wish to impart.&nbsp;</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2007/09/c-string-manipulation-string-constructors-string-assignment-and-the-stringbuilder-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generate unique strings and numbers in C#</title>
		<link>http://www.csharphelp.com/2007/09/generate-unique-strings-and-numbers-in-c/</link>
		<comments>http://www.csharphelp.com/2007/09/generate-unique-strings-and-numbers-in-c/#comments</comments>
		<pubDate>Wed, 19 Sep 2007 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Strings]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=671</guid>
		<description><![CDATA[The&#160;System.Guid is used whenever we need to generate a unique key, but it is very long. That&#39;s in many cases not an issue, but in a web scenario where it is part of the URL we need to use its string representation which is 36 characters long. It clutters up the URL and is just [...]]]></description>
			<content:encoded><![CDATA[<p><span class="smallblack"> The&nbsp;<a target="_new" href="http://msdn2.microsoft.com/en-us/library/system.guid.aspx">System.Guid</a> is used whenever we need to generate a unique key, but it is very long. That&#39;s in many cases not an issue, but in a web scenario where it is part of the URL we need to use its string representation which is 36 characters long. It clutters up the URL and is just basically ugly.</span></p>
<p><span class="smallblack"> It is not possible to shorten it without loosing some of the uniqueness of the GUID, but we can come a long way if we can accept a 16 character string instead.</span></p>
<p><span class="smallblack"> We can change the standard GUID string representation:</span></p>
<p><span class="smallblack"> <em>21726045-e8f7-4b09-abd8-4bcc926e9e28</em></span></p>
<p><span class="smallblack"> Into a shorter string:</span></p>
<p><span class="smallblack"> <em>3c4ebc5f5f2c4edc</em></span></p>
<p><span class="smallblack"> The following method creates the shorter string and it is&nbsp;actually very&nbsp;unique. An iteration of 10 million didn.t create a duplicate. It uses the uniqueness of a GUID to create the string.</span></p>
<p><span class="smallblack"> <span style="font-size:11px;color:black;font-family:Courier New;background-color:transparent;"><span style="font-size:11px;color:blue;font-family:Courier New;background-color:transparent;">private</span> <span style="font-size:11px;color:blue;font-family:Courier New;background-color:transparent;">string</span> GenerateId()<br /> {<br /> <span style="font-size:11px;color:blue;font-family:Courier New;background-color:transparent;">&nbsp;long</span> i <span style="font-size:11px;color:red;font-family:Courier New;background-color:transparent;">=</span> 1;<br /> <span style="font-size:11px;color:blue;font-family:Courier New;background-color:transparent;">&nbsp;foreach</span> (<span style="font-size:11px;color:blue;font-family:Courier New;background-color:transparent;">byte</span> b <span style="font-size:11px;color:blue;font-family:Courier New;background-color:transparent;">in</span> Guid.NewGuid().ToByteArray())<br /> &nbsp;{<br /> &nbsp; i *= ((<span style="font-size:11px;color:blue;font-family:Courier New;background-color:transparent;">int</span>)b <span style="font-size:11px;color:red;font-family:Courier New;background-color:transparent;">+</span> 1);<br /> &nbsp;}<br /> <span style="font-size:11px;color:blue;font-family:Courier New;background-color:transparent;">&nbsp;return</span> <span style="font-size:11px;color:blue;font-family:Courier New;background-color:transparent;">string</span>.Format(<span style="font-size:11px;color:#666666;font-family:Courier New;background-color:#e4e4e4;">&quot;{0:x}&quot;</span>, i <span style="font-size:11px;color:red;font-family:Courier New;background-color:transparent;">-</span> DateTime.Now.Ticks);<br /> }</p>
<p> </span></span></p>
<p><span class="smallblack"> If you instead want numbers instead of a string, you can do that to but then you need to go up to 19 characters. The following method converts a GUID to an Int64.</span></p>
<p><span class="smallblack"> <span style="font-size:11px;color:black;font-family:Courier New;background-color:transparent;"><span style="font-size:11px;color:blue;font-family:Courier New;background-color:transparent;">private</span> <span style="font-size:11px;color:blue;font-family:Courier New;background-color:transparent;">long</span> GenerateId()<br /> {<br /> <span style="font-size:11px;color:blue;font-family:Courier New;background-color:transparent;">&nbsp;byte</span>[] buffer <span style="font-size:11px;color:red;font-family:Courier New;background-color:transparent;">=</span> Guid.NewGuid().ToByteArray();<br /> <span style="font-size:11px;color:blue;font-family:Courier New;background-color:transparent;">&nbsp;return</span> BitConverter.ToInt64(buffer, 0);<br /> }</p>
<p> </span></span></p>
<p><span class="smallblack"> The standard GUID is still the best way to ensure the uniqueness even though it isn&#39;t 100% unique.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2007/09/generate-unique-strings-and-numbers-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Strings and Regular Expressions</title>
		<link>http://www.csharphelp.com/2007/05/c-strings-and-regular-expressions/</link>
		<comments>http://www.csharphelp.com/2007/05/c-strings-and-regular-expressions/#comments</comments>
		<pubDate>Sun, 13 May 2007 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Regex]]></category>
		<category><![CDATA[Strings]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=542</guid>
		<description><![CDATA[3.0. Introduction It would be very rare to create an entireapplication without using a single string. Strings help make sense ofthe seemingly random jumble of binary data that applications use toaccomplish a task. They appear in all facets of application developmentfrom the smallest system utility to large enterprise services. Theirvalue is so apparent that more [...]]]></description>
			<content:encoded><![CDATA[<h2><span class="smallblack">3.0. Introduction</span></h2>
<p><span class="smallblack">It would be very rare to create an entireapplication without using a single string. Strings help make sense ofthe seemingly random jumble of binary data that applications use toaccomplish a task. They appear in all facets of application developmentfrom the smallest system utility to large enterprise services. Theirvalue is so apparent that more and more connected systems are leaningtoward string data within their communication protocols by utilizingthe Extensible Markup Language (XML) rather than the more cumbersometraditional transmission of large binary data. This book uses stringsextensively to examine the internal contents of variables and theresults of program flow using Framework Class Libraries (FCL) methodssuch as <tt>Console.WriteLine</tt> and <tt>MessageBox.Show</tt>.</span></p>
<p><span class="smallblack">In this chapter, you will learn how to takeadvantage of the rich support for strings within the .NET Framework andthe C# language. Coverage includes ways to manipulate string contents,programmatically inspect strings and their character attributes, andoptimize performance when working with string objects. Furthermore,this chapter uncovers the power of regular expressions and how theyallow you to effectively parse and manipulate string data. Afterreading this chapter, you will be able to use regular expressions in avariety of different situations where their value is apparent.</span></p>
<p><span class="smallblack"><a name="Heading3"></a></span></p>
<h2><span class="smallblack">3.1. Creating and Using String Objects</span></h2>
<p><span class="smallblack"><b>You want to create and manipulate string data within your application.</b></span></p>
<p><span class="smallblack"><a name="Heading4"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">The C# language, knowing the importance of string data, contains a <tt>string</tt> keyword that simulates the behavior of a value data type. To create a string, declare a variable using the <tt>string</tt>keyword. You can use the assignment operator to initialize the variableusing a static string or with an already initialized string variable.</span></p>
<p><span class="smallblack">string string1 = &quot;This is a string&quot;;<br />string string2 = string1;</span>
<p><span class="smallblack">To gain more control over string initialization, declare a variable using the <tt>System.String</tt> data type and create a new instance using the <tt>new</tt><i> </i>keyword. The <tt>System.String</tt>class contains several constructors that you can use to initialize thestring value. For instance, to create a new string that is a smallsubset of an existing string, use the overloaded constructor, whichtakes a character array and two integers denoting the beginning indexand the number of characters from that index to copy:</span></p>
<p><span class="smallblack">class Class1<br />{<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> string string1 = &quot;Field1, Field2&quot;;<br /> System.String string2 = new System.String( string1.ToCharArray(), 8, 6 );</p>
<p> Console.WriteLine( string2 );</p>
<p> }<br />}</span>
<p><span class="smallblack">Finally, if you know a string will be intensively manipulated, use the <tt>System.Text. StringBuilder</tt> class. Creating a variable of this data type is similar to using the <tt>System.String</tt>class, and it contains several constructors to initialize the internalstring value. The key internal difference between a regular stringobject and a <tt>StringBuilder</tt><i> </i>lies in performance.Whenever a string is manipulated in some manner, a new object has to becreated, which subsequently causes the old object to be marked fordeletion by the garbage collector. For a string that undergoes severaltransformations, the performance hit associated with frequent objectcreation and deletions can be great. The <tt>StringBuilder</tt><i> </i>class,on the other hand, maintains an internal buffer, which expands to makeroom for more string data should the need arise, thereby decreasingfrequent object activations.</span></p>
<p><span class="smallblack"><a name="Heading5"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">There is no recommendation on whether you use the <tt>string</tt> keyword or the <tt>System.String</tt> class. The <tt>string</tt><i> </i>keyword is simply an alias for this class, so it is all a matter of taste. We prefer using the <tt>string</tt> keyword, but this preference is purely aesthetic. For this reason, we simply refer to the <tt>System.String</tt> class as the <tt>string</tt> class or data type.</span></p>
<p><span class="smallblack">The <tt>string</tt> class contains manymethods, both instance and static, for manipulating strings. If youwant to compare strings, you can use the <tt>Compare</tt> method. If you are just testing for equality, then you might want to use the overloaded equality operator (<tt>==</tt>). However, the <tt>Compare</tt>method returns an integer instead of Boolean value denoting how the twostrings differ. If the return value is 0, then the strings are equal.If the return value is greater than 0, as shown in Listing 3.1, thenthe first operand is greater alphabetically than the second operand. Ifthe return value is less than 0, the opposite is true. When a string issaid to be alphabetically greater or lower than another, each characterreading from left to right from both strings is compared using itsequivalent ASCII value. </span></p>
<h4><span class="smallblack"> Listing 3.1 Using the Compare Method in the <tt>String</tt> Class </span></h4>
<p><span class="smallblack">using System;</p>
<p>namespace _1_UsingStrings<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> string string1 = &quot;&quot;;<br /> String string2 = &quot;&quot;;</p>
<p> Console.Write( &quot;Enter string 1: &quot; );<br /> string1 = Console.ReadLine();<br /> Console.Write( &quot;Enter string 2: &quot; );<br /> string2 = Console.ReadLine();</p>
<p> // string and String are the same types<br /> Console.WriteLine( &quot;string1 is a {0}\nstring2 is a {1}&quot;, <br /> string1.GetType().FullName, string2.GetType().FullName );</p>
<p> CompareStrings( string1, string2 );<br /> }</p>
<p> public static void CompareStrings( string str1, string str2 )<br /> {<br /> int compare = String.Compare( str1, str2 );</p>
<p> if( compare == 0 )<br /> {<br /> Console.WriteLine( &quot;The strings {0} and {1} are the same.\n&quot;,<br /> str1, str2 );<br /> }<br /> else if( compare &lt; 0 )<br /> {<br /> Console.WriteLine( &quot;The string {0} is less than {1}&quot;,<br /> str1, str2 );<br /> }<br /> else if( compare &gt; 0 )<br /> {<br /> Console.WriteLine( &quot;The string {0} is greater than {1}&quot;,<br /> str1, str2 );<br /> }<br /> }<br /> }<br />}</span>
<p><span class="smallblack">As mentioned earlier, the <tt>string</tt>class contains both instance and static methods. Sometimes you have nochoice about whether to use an instance or static method. However, afew of the instance methods contain a static version as well. Becausecalling a static method is a nonvirtual function call, you seeperformance gains if you use this version. An example where you mightsee both instance and static versions appears in Listing 3.1. Thestring comparison uses the static <tt>Compare</tt> method. You can also do so using the nonstatic <tt>CompareTo</tt>method using one of the string instances passed in as parameters. Inmost cases, the performance gain is negligible, but if an applicationneeds to repeatedly call these methods, you might want to considerusing the static over the non-static method.</span></p>
<p><span class="smallblack">The <tt>string</tt> class is immutable. Once a string is created, it cannot be manipulated. Methods within the <tt>string</tt>class that modify the original string instance actually destroy thestring and create a new string object rather than manipulate theoriginal string instance. It can be exp</p>
<p>ensive t<br />
o repeatedly call <tt>string</tt> methods if new objects are created and destroyed continuously. To solve this, the .NET Framework contains a <tt>StringBuilder</tt> class contained within the <tt>System.Text</tt> namespace, which is explained later in this chapter.</span></p>
<p><span class="smallblack"><a name="Heading6"></a></span></p>
<h2><span class="smallblack">3.2. Formatting Strings</span></h2>
<p><span class="smallblack"><b>Given one or more objects, you want to create a single formatted string representation.</b></span></p>
<p><span class="smallblack"><a name="Heading7"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">You can format strings using numeric and picture formatting within <tt>String.Format</tt> or within any method that uses string-formatting techniques for parameters such as <tt>Console.WriteLine</tt>.</span></p>
<p><span class="smallblack"><a name="Heading8"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">The <tt>String</tt> class as well as a fewother methods within the .NET Framework allow you to format strings topresent them in a more ordered and readable format. Up to this point inthe book, we used basic formatting when calling the <tt>Console.WriteLine</tt> method. The first parameter to <tt>Console.WriteLine</tt>is the format specifier string. This string controls how the remainingparameters to the method should appear when displayed. You useplaceholders within the format string to insert the value of avariable. This placeholder uses the syntax <tt>{</tt>n<tt>}</tt> where n is the index in the parameter list following the format specifier. Take the following line of code, for instance:</span></p>
<p><span class="smallblack">Console.WriteLine( &quot;x={0}, y={1}, {0}+{1}={2}&quot;, x, y, x+y );</span>
<p><span class="smallblack">This line of code has three parametersfollowing the format specifier string. You use placeholders within theformat specification, and when this method is called, the appropriatesubstitutions are made. Although you can do the same thing using stringconcatenation, the resultant line of code is slightly obfuscated:</span></p>
<p><span class="smallblack">string s = &quot;x=&quot; + x + &quot;,y=&quot; + y + &quot;, &quot; + x + &quot;+&quot; + y + &quot;=&quot; + (x+y);<br />Console.WriteLine( s );</span>
<p><span class="smallblack">You can further refine the format byapplying format attributes on the placeholders themselves. Theseadditional attributes follow the parameter index value and areseparated from that index with a <tt>:</tt> character. There are twotypes of special formatting available. The first is numeric formatting,which lets you format a numeric parameter into one of nine differentnumeric formats, as shown in Table 3.1. The format of these specifiers,using the currency format as an example, is <tt>C</tt>xx<i> </i>where xx<i> </i>is a number from 1 to 99 specifying the number of digits to display.<i> </i>Listing3.2 shows how to display an array of integers in hexadecimal format,including how to specify the number of digits to display. Notice alsohow you can change the case of the hexadecimal numbers A through F byusing an uppercase or lowercase format specifier.</span></p>
<h4><span class="smallblack"> Table 3.1 Numeric Formatting Specifiers</span></h4>
<table border="2" cellpadding="2" cellspacing="2">
<colgroup>
<col width="68"></col>
<col width="139"></col>
<col width="234"></col>
</colgroup>
<tbody>
<tr valign="TOP">
<td valign="TOP">
<p><b>Character</b></p>
</td>
<td valign="TOP">
<p><b>Format</b></p>
</td>
<td valign="TOP">
<p><b>Description</b></p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>C</tt> or <tt>c</tt></p>
</td>
<td valign="TOP">
<p>Currency</p>
</td>
<td valign="TOP">
<p>Culturally aware currency format.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>D</tt> or <tt>d</tt></p>
</td>
<td valign="TOP">
<p>Decimal</p>
</td>
<td valign="TOP">
<p>Only supports integral numbers. Displays a string using decimal digits preceded by a minus sign if negative.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>E</tt> or <tt>e</tt></p>
</td>
<td valign="TOP">
<p>Exponential/scientific notation</p>
</td>
<td valign="TOP">
<p>Displays numbers in the form <tt>&plusmn;</tt>d<tt>.</tt>dddddd<tt>E&plusmn;</tt>dd where d is a decimal digit. </p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>F</tt> or <tt>f</tt></p>
</td>
<td valign="TOP">
<p>Fixed point</p>
</td>
<td valign="TOP">
<p>Displays a series of decimal digits with a decimal point and additional digits.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>G</tt> or <tt>g</tt></p>
</td>
<td valign="TOP">
<p>General format</p>
</td>
<td valign="TOP">
<p>Displays either as a fixed-point or scientific notation based on the size of the number.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>N</tt> or <tt>n</tt></p>
</td>
<td valign="TOP">
<p>Number format</p>
</td>
<td valign="TOP">
<p>Similar to fixed point but uses a separator character (such as <tt>,</tt>) for groups of digits.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>P</tt> or <tt>p</tt></p>
</td>
<td valign="TOP">
<p>Percentage</p>
</td>
<td valign="TOP">
<p>Multiplies the number by 100 and displays with a percent symbol.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>R</tt> or <tt>r</tt></p>
</td>
<td valign="TOP">
<p>Roundtrip</p>
</td>
<td valign="TOP">
<p>Formats a floating-point number so that it can be successfully converted back to its original value.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>X</tt> or <tt>x</tt></p>
</td>
<td valign="TOP">
<p>Hexadecimal</p>
</td>
<td valign="TOP">
<p>Displays an integral number using the base-16 number system.</p>
</td>
</tr>
</tbody>
</table>
<p><span class="smallblack"><br /></span></p>
<h4><span class="smallblack"> Listing 3.2 Specifying a Different Numeric Format by Adding Format Specifiers on a Parameter Placeholder </span></h4>
<p><span class="smallblack">using System;</p>
<p>namespace _2_Formatting<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> double[] numArray = {2, 5, 4.5, 45.43, 200000};</p>
<p> // format in lowercase hex<br /> Console.WriteLine( &quot;\n\nHex (lower)\n&#8212;&#8212;&#8212;&#8211;&quot; );<br /> foreach( double num in numArray )<br /> {<br /> Console.Write( &quot;0x{0:x}\t&quot;, (int) num );<br /> }</p>
<p> // format in uppercase hex<br /> Console.WriteLine( &quot;\n\nHex (upper)\n&#8212;&#8212;&#8212;&#8211;&quot; );<br /> foreach( double num in numArray )<br /> {<br /> Console.Write( &quot;0x{0:X}\t&quot;, (int) num );<br /> }<br /> }<br /> }<br />}</span>
<p><span class="smallblack">Another type of formatting is <i>picture</i>formatting. Picture formatting allows you to create a custom formatspecifier using various symbols within the format specifier string.Table 3.2 lists the available picture format characters. Listing 3.3also shows how to create a custom format specifier. In that code, thedigits of the input number are extracted and displayed using acombination of digit placeholders and a decimal-point specifier.Furthermore, you can see that you are free to add characters not listedin the table. This freedom allows you to add literal charactersintermixed with the digits.</span></p>
<h4><span class="smallblack"> Table 3.2 Picture Formatting Specifiers</span></h4>
<table border="2" cellpadding="2" cellspacing="2">
<colgroup>
<col width="60"></col>
<col width="144"></col>
<col width="238"></col>
</colgroup>
<tbody>
<tr valign="TOP">
<td valign="TOP">
<p><b><b>Character</b></b></p>
</td>
<td valign="TOP">
<p><b><b>Name</b></b></p>
</td>
<td valign="TOP">
<p><b><b>Description</b></b></p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>0</tt></p>
</td>
<td valign="TOP">
<p>Zero placeholder</p>
</td>
<td valign="TOP">
<p>Copies a digit to the result string if a digit is at the position of the <tt>0</tt>. If no digit is present, a 0 is displayed.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>#</tt></p>
</td>
<td valign="TOP">
<p>Display digit placeholder</p>
</td>
<td valign="TOP">
<p>Copies a digit to the result string if a digit appears at the position of the <tt>#</tt>. If no digit is present, nothing is displayed.</p>
</td>
</tr</p>
<p>><br />
<tr valign="TOP">
<td valign="TOP">
<p><tt>.</tt></p>
</td>
<td valign="TOP">
<p>Decimal point</p>
</td>
<td valign="TOP">
<p>Represents the location of the decimal point in the resultant string.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>,</tt></p>
</td>
<td valign="TOP">
<p>Group separator and number scaling</p>
</td>
<td valign="TOP">
<p>Inserts thousands separators if placed between two placeholders or scales a number down by 1,000 per <tt>,</tt> character when placed directly to the left of a decimal point.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>&amp;</tt></p>
</td>
<td valign="TOP">
<p>Percent</p>
</td>
<td valign="TOP">
<p>Multiplies a number by 100 and inserts a <tt>%</tt> symbol.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>E&plusmn;0</tt>, <tt>e&plusmn;0</tt></p>
</td>
<td valign="TOP">
<p>Exponential notation</p>
</td>
<td valign="TOP">
<p>Displays the number in exponential notation using the number of 0s as a placeholder for the exponent value.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\</tt></p>
</td>
<td valign="TOP">
<p>Escape character</p>
</td>
<td valign="TOP">
<p>Used to specify a special escape-character formatting instruction. Some of these include <tt>\n</tt> for newline, <tt>\t</tt> for tab, and <tt>\</tt> for the <tt>\</tt> character.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>;</tt></p>
</td>
<td valign="TOP">
<p>Section separator</p>
</td>
<td valign="TOP">
<p>Separates positive, negative, and zero numbers in the format stringin which you can apply different formatting rules based on the sign ofthe original number.</p>
</td>
</tr>
</tbody>
</table>
<p><span class="smallblack"><br /></span></p>
<p><span class="smallblack">Listing 3.3 shows how custom formatting can separate a number by its decimal point. Using a <tt>foreach</tt><i> </i>loop,each value is printed using three different formats. The first formatwill output the value&#39;s integer portion using the following formatstring:</span></p>
<p><span class="smallblack">0:$#,#</span>
<p><span class="smallblack">Next, the decimal portion is written. Ifthe value does not explicitly define a decimal portion, zeroes arewritten instead. The format string to output the decimal value is</span></p>
<p><span class="smallblack">$.#0;</span>
<p><span class="smallblack">Finally, the entire value is displayed up to two decimal places using the following format string:</span></p>
<p><span class="smallblack">{0:$#,#.00}</span><br />
<h4><span class="smallblack"> Listing 3.3 Using Picture Format Specifiers to Create Special Formats </span></h4>
<p><span class="smallblack">using System;</p>
<p>namespace _2_Formatting<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> double[] numArray = {2, 5, 4.5, 45.43, 200000};</p>
<p> // format as custom<br /> Console.WriteLine( &quot;\n\nCustom\n&#8212;&#8212;&quot; );<br /> foreach( double num in numArray )<br /> {<br /> Console.WriteLine( &quot;{0:$#,# + $.#0;} = {0:$#,#.00}&quot;, num );<br /> }<br /> }<br /> }<br />}</span>
<p><span class="smallblack"><a name="Heading9"></a></span></p>
<h2><span class="smallblack">3.3. Accessing Individual String Characters</span></h2>
<p><span class="smallblack"><b>You want to process individual characters within a string.</b></span></p>
<p><span class="smallblack"><a name="Heading10"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">Use the index operator (<tt>[]</tt>) byspecifying the zero-based index of the character within the string thatyou want to extract. Furthermore, you can also use the <tt>foreach</tt> enumerator on the string using a <tt>char</tt> structure as the enumeration data type.</span></p>
<p><span class="smallblack"><a name="Heading11"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">The <tt>string</tt> class is really acollection of objects. These objects are individual characters. You canaccess each character using the same methods you would use to access anobject in most other collections (which is covered in the next chapter).</span></p>
<p><span class="smallblack">You use an indexer to specify which objectin a collection you want to retrieve. In C#, the first object begins atthe 0 index of the string. The objects are individual characters whosedata type is <tt>System.Char</tt>, which is aliased with the <tt>char</tt> keyword. The indexer for the <tt>string</tt>class, however, can only access a character and cannot set the value ofa character at that position. Because a string is immutable, you cannotchange the internal array of characters unless you create and return anew string. If you need the ability to index a string to set individualcharacters, use a <tt>StringBuilder</tt> object.</span></p>
<p><span class="smallblack">Listing 3.4 shows how to access thecharacters in a string. One thing to point out is that because thestring also implements the <tt>IEnumerable</tt><i> </i>interface, you can use the <tt>foreach</tt> control structure to enumerate through the string.</span></p>
<h4><span class="smallblack">Listing 3.4<b> Accessing Characters Using Indexers and Enumeration </b></span></h4>
<p><span class="smallblack">using System;<br />using System.Text;</p>
<p>namespace _3_Characters<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> string str = &quot;abcdefghijklmnopqrstuvwxyz&quot;;</p>
<p> str = ReverseString( str );<br /> Console.WriteLine( str );</p>
<p> str = ReverseStringEnum( str );<br /> Console.WriteLine( str );<br /> }</p>
<p> static string ReverseString( string strIn )<br /> {<br /> StringBuilder sb = new StringBuilder(strIn.Length);</p>
<p> for( int i = 0; i &lt; strIn.Length; ++i )<br /> {<br /> sb.Append( strIn[(strIn.Length-1)-i] );<br /> }<br /> return sb.ToString();<br /> }</p>
<p> static string ReverseStringEnum( string strIn )<br /> {<br /> StringBuilder sb = new StringBuilder( strIn.Length );<br /> foreach( char ch in strIn )<br /> {<br /> sb.Insert( 0, ch );<br /> }</p>
<p> return sb.ToString();<br /> }<br /> }<br />}</span>
<p><span class="smallblack"><a name="Heading12"></a></span></p>
<h2><span class="smallblack">3.4. Analyzing Character Attributes</span></h2>
<p><span class="smallblack"><b>You want to evaluate the individual characters in a string to determine a character&#39;s attributes.</b></span></p>
<p><span class="smallblack"><a name="Heading13"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">The <tt>System.Char</tt> structure containsseveral static functions that let you test individual characters. Youcan test whether a character is a digit, letter, or punctuation symbolor whether the character is lowercase or uppercase.</span></p>
<p><span class="smallblack"><a name="Heading14"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">One of the hardest issues to handle whenwriting software is making sure users input valid data. You can usemany different methods, such as restricting input to only digits, butultimately, you always need an underlying validating test of the inputdata. </span></p>
<p><span class="smallblack">You can use the <tt>System.Char</tt><i> </i>structure to perform a variety of text-validation procedures. Listing 3.5 demonstrates validating user input as well as inspecting the characteristics of a character. It begins by displaying a menu and then waiting for user input using the <tt>Console.ReadLine</tt><i> </i>method. Once a user enters a command, you make a check using the method <tt>ValidateMainMenuInput</tt>. This method checks to make sure the first character in the input string is not a digit or punctuation symbol. If the validation passes, the string is passed to a method that inspects each character in the input string. This method simply enumerates through all the characters in the input string and prints descriptive messages based on the characteristics. Some of the <tt>System.Char</tt> methods for inspection have been inadvertently left out of Listing 3.5. Table 3.3 shows the remaining methods and their functionality. The results of runnin</p>
<p>g the application in Listing 3.5 appear in <a href="http://www.csharphelp.com/archives3/files/archive561/03Fig01.jpg">Figure 3.1</a>.</span></p>
<h4><span class="smallblack"> Listing 3.5 Using the Static Methods in <tt>System.Char</tt> to Inspect the Details of a Single Character</span></h4>
<p><span class="smallblack">using System;</p>
<p>namespace _4_CharAttributes<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> char cmd = &#39;x&#39;;</p>
<p> string input;<br /> do<br /> {<br /> DisplayMainMenu();<br /> input = Console.ReadLine();</p>
<p> if( (input == &quot;&quot; ) || <br /> ValidateMainMenuInput( Char.ToUpper(input[0]) ) == 0 )<br /> {<br /> Console.WriteLine( &quot;Invalid command!&quot; );<br /> }<br /> else<br /> {<br /> cmd = Char.ToUpper(input[0]);</p>
<p> switch( cmd )<br /> {<br /> case &#39;Q&#39;:<br /> {<br /> break;<br /> }</p>
<p> case &#39;N&#39;:<br /> {<br /> Console.Write( &quot;Enter a phrase to inspect: &quot; );<br /> input = Console.ReadLine();<br /> InspectPhrase( input );<br /> break;<br /> }<br /> }<br /> }<br /> } while ( cmd != &#39;Q&#39; );<br /> }</p>
<p> private static void InspectPhrase( string input )<br /> {<br /> foreach( char ch in input )<br /> {<br /> Console.Write( ch + &quot; &#8211; &quot;);</p>
<p> if( Char.IsDigit(ch) )<br /> Console.Write( &quot;IsDigit &quot; );<br /> if( Char.IsLetter(ch) )<br /> {<br /> Console.Write( &quot;IsLetter &quot; );<br /> Console.Write( &quot;(lowercase={0}, uppercase={1})&quot;, <br /> Char.ToLower(ch), Char.ToUpper(ch));<br /> }<br /> if( Char.IsPunctuation(ch) )<br /> Console.Write( &quot;IsPunctuation &quot; );<br /> if( Char.IsWhiteSpace(ch) )<br /> Console.Write( &quot;IsWhitespace&quot; );</p>
<p> Console.Write(&quot;\n&quot;);</p>
<p> }<br /> }<br /> private static int ValidateMainMenuInput( char input )<br /> {<br /> // a simple check to see if input == &#39;N&#39; or &#39;Q&#39; is good enough<br /> // the following is for illustrative purposes<br /> if( Char.IsDigit( input ) == true )<br /> return 0;<br /> else if ( Char.IsPunctuation( input ) )<br /> return 0;<br /> else if( Char.IsSymbol( input ))<br /> return 0;<br /> else if( input != &#39;N&#39; &amp;&amp; input != &#39;Q&#39; )<br /> return 0;</p>
<p> return (int) input;<br /> }</p>
<p> private static void DisplayMainMenu()<br /> {<br /> Console.WriteLine( &quot;\nPhrase Inspector\n&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-&quot; );<br /> Console.WriteLine( &quot;N)ew Phrase&quot; );<br /> Console.WriteLine( &quot;Q)uit\n&quot; );<br /> Console.Write( &quot;&gt;&gt; &quot; );<br /> }<br /> }<br />}</span><br />
<h4><span class="smallblack"> Table 3.3 <tt>System.Char</tt> Inspection Methods</span></h4>
<table border="2" cellpadding="2" cellspacing="2">
<colgroup>
<col width="113"></col>
<col width="329"></col>
</colgroup>
<tbody>
<tr valign="TOP">
<td valign="TOP">
<p><b><tt>Name</tt></b></p>
</td>
<td valign="TOP">
<p><b><b>Description</b></b></p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsControl</tt></p>
</td>
<td valign="TOP">
<p>Denotes a control character such as a tab or carriage return.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsDigit</tt></p>
</td>
<td valign="TOP">
<p>Indicates a single decimal digit.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsLetter</tt></p>
</td>
<td valign="TOP">
<p>Used for alphabetic characters.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsLetterOrDigit</tt></p>
</td>
<td valign="TOP">
<p>Returns <tt>true</tt> if the character is a letter or a digit.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsLower</tt></p>
</td>
<td valign="TOP">
<p>Used to determine whether a character is lowercase.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsNumber</tt></p>
</td>
<td valign="TOP">
<p>Tests whether a character is a valid number.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsPunctuation</tt></p>
</td>
<td valign="TOP">
<p>Denotes whether a character is a punctuation symbol.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsSeparator</tt></p>
</td>
<td valign="TOP">
<p>Denotes a character used to separate strings. An example is the space character.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsSurrogate</tt></p>
</td>
<td valign="TOP">
<p>Checks for a Unicode surrogate pair, which consists of two 16-bit values primarily used in localization contexts.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsSymbol</tt></p>
</td>
<td valign="TOP">
<p>Used for symbolic characters such as <tt>$</tt> or <tt>#</tt>.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsUpper</tt></p>
</td>
<td valign="TOP">
<p>Used to determine whether a character is uppercase.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsWhiteSpace</tt></p>
</td>
<td valign="TOP">
<p>Indicates a character classified as whitespace such as a space character, tab, or carriage return.</p>
</td>
</tr>
</tbody>
</table>
<p><span class="smallblack"><br /></span></p>
<p><span class="smallblack"><a href="http://www.csharphelp.com/archives3/files/archive561/03Fig01.jpg"><b>Figure 3.1</b></a><br />Use the <tt>static</tt> method in the <tt>System.Char</tt> class to inspect character attributes.</span></p>
<p><span class="smallblack">The <tt>System.Char</tt> structure isdesigned to work with a single Unicode character. Because a Unicodecharacter is 2 bytes, the range of a character is from 0 to 0xFFFF. Forportability reasons in future systems, you can always check the size ofa <tt>char</tt> by using the <tt>MaxValue</tt> constant declared in the <tt>System.Char</tt><i> </i>structure. One thing to keep in mind when working with characters is to avoid the confusion of mixing <tt>char</tt>types with integer types. Characters have an ordinal value, which is aninteger value used as a lookup into a table of symbols. One example ofa table is the ASCII table, which contains 255 characters and includesthe digits 0 through 9, letters, punctuation symbols, and formattingcharacters. The confusion lies in the fact that the number 6, forinstance, has an ordinal <tt>char</tt> value of 0&#215;36. Therefore, the line of code meant to initialize a character to the number 6</span></p>
<p><span class="smallblack">char ch = (char) 6;</span>
<p><span class="smallblack">is wrong because the actual character inthis instance is ^F, the ACK control character used in modemhandshaking protocols. Displaying this value in the console would notprovide the 6 that you were looking for. You could have chosen twodifferent methods to initialize the variable. The first way is</span></p>
<p><span class="smallblack">char ch = (char) 0&#215;36;</span>
<p><span class="smallblack">which produces the desired result and prints the number 6 to the console if passed to the <tt>Console.Write</tt> method. However, unless you have the ASCII table memorized, this procedure can be cumbersome. To initialize a <tt>char</tt><i> </i>variable, simply place the value between single quotes: </span></p>
<p><span class="smallblack">char ch = &#39;6&#39;;</span>
<p><span class="smallblack"><a name="Heading15"></a></span></p>
<h2><span class="smallblack">3.5. Case-Insensitive String Comparison</span></h2>
<p><span class="smallblack"><b>You want to perform case-insensitive string comparison on two strings.</b></span></p>
<p><span class="smallblack"><a name="Heading16"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">Use the overloaded <tt>Compare</tt> method in the <tt>System.String</tt> class which accepts a Boolean value, <tt>ignoreCase</tt>, as the last parameter. This parameter specifies whether the comparison should be case insensitive (<tt>true</tt>) or case sensitive (<tt>false</tt>). To compare single characters, convert them to uppercase or lowercase, using <tt>ToUpper</tt><i> </i>or <tt>ToLower</tt>, and then perform the comparison.</span></p>
<p><span class="smallblack"><a name="Heading17"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">Validating user input requires a lot offorethought into the possible values a user can enter. Making sure youcover the range of possible values can be a daunting task, and you</p>
<p>might ultimately run into human-computer interaction issues by severelylimiting what a user can enter. Case-sensitivity issues increase thepossible range of values, leading to greater security with respect tosuch things as passwords, but this security is usually at the expenseof a user&#39;s frustration when she forgets whether a character iscapitalized. As with many other programming problems, you must weighthe pros and cons.</span></p>
<p><span class="smallblack">To perform a case-insensitive comparison, you can use one of the many overloaded <tt>Compare</tt> methods within the <tt>System.String</tt>class. The methods that allow you to ignore case issues use a Booleanvalue as the last parameter in the method. This parameter is named <tt>ignoreCase</tt>, and when you set it to <tt>true</tt>, you make a case-insensitive comparison, as demonstrated in Listing 3.6.</span></p>
<h4><span class="smallblack"> Listing 3.6 Performing a Case-Insensitive String Comparison </span></h4>
<p><span class="smallblack">using System;</p>
<p>namespace _5_CaseComparison<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> string str1 = &quot;This Is A String.&quot;;<br /> string str2 = &quot;This is a string.&quot;;</p>
<p> Console.WriteLine( &quot;Case sensitive comparison of&quot; +<br /> &quot; str1 and str2 = {0}&quot;, String.Compare( str1, str2 ));</p>
<p> Console.WriteLine( &quot;Case insensitive comparison of&quot; + <br /> &quot; str1 and str2 = {0}&quot;, String.Compare( str1, str2, true ));<br /> }<br /> }<br />}</span>
<p><span class="smallblack"><a name="Heading18"></a></span></p>
<h2><span class="smallblack">3.6. Working with Substrings</span></h2>
<p><span class="smallblack"><b>You need to change or extract a specific portion of a string.</b></span></p>
<p><span class="smallblack"><a name="Heading19"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">To copy a portion of a string into a new string, use the <tt>SubString</tt> method within the <tt>System.String</tt><i> </i>class. You call this method using the string object instance of the source string:</span></p>
<p><span class="smallblack">string source = &quot;ABCD1234WXYZ&quot;;<br />string dest = source.Substring( 4, 4 );<br />Console.WriteLine( &quot;{0}\n&quot;, dest );</span>
<p><span class="smallblack">To copy a substring into an already existing character array, use the <tt>CopyTo</tt> method. To assign a character array to an existing string object, create a new instance of the string using the <tt>new</tt><i> </i>keyword, passing the character array as a parameter to the string constructor as shown in the following code, whose ouput appears in <a href="http://www.csharphelp.com/archives3/files/archive561/03Fig02.jpg">Figure 3.2</a>:</span></p>
<p><span class="smallblack">string source = &quot;ABCD&quot;;<br />char [] dest = { &#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;, &#39;8&#39; };</p>
<p>Console.Write( &quot;Char array before = &quot; );<br />Console.WriteLine( dest );</p>
<p>// copy substring into char array<br />source.CopyTo( 0, dest, 4, source.Length );</p>
<p>Console.Write( &quot;Char array after = &quot; );<br />Console.WriteLine( dest );</p>
<p>// copy back into source string<br />source = new String( dest );</p>
<p>Console.WriteLine( &quot;New source = {0}\n&quot;, source ); </span>
<p><span class="smallblack"> <a href="http://www.csharphelp.com/archives3/files/archive561/03Fig02.jpg"><b>Figure 3.2 </b></a><br /> Use the <tt>CopyTo</tt> method to copy a substring into an existing character array.</span></p>
<p><span class="smallblack">If you need to remove a substring within a string and replace it with a different substring, use the <tt>Replace</tt><i> </i>method. This method accepts two parameters, the substring to replace and the string to replace it with:</span></p>
<p><span class="smallblack">string replaceStr = &quot;1234&quot;;<br />string dest = &quot;ABCDEFGHWXYZ&quot;;</p>
<p>dest = dest.Replace( &quot;EFGH&quot;, replaceStr );</p>
<p>Console.WriteLine( dest );</span>
<p><span class="smallblack">To extract an array of substrings that are separated from each other by one or more delimiters, use the <tt>Split</tt> method. This method uses a character array of delimiter characters and returns a string array of each substring within the original string as shown in the following code, whose output appears in <a href="http://www.csharphelp.com/archives3/files/archive561/03Fig03.jpg">Figure 3.3</a>. You can optionally supply an integer specifying the maximum number of substrings to split:</span></p>
<p><span class="smallblack">char delim = &#39;\&#39;;<br />string filePath = &quot;C:\Windows\Temp&quot;;<br />string [] directories = null;</p>
<p>directories = filePath.Split( delim );</p>
<p>foreach (string directory in directories) <br />{<br /> Console.WriteLine(&quot;{0}&quot;, directory);<br />}</span>
<p><span class="smallblack"> <a href="http://www.csharphelp.com/archives3/files/archive561/03Fig03.jpg"><b>Figure 3.3 </b></a><br /> You can use the <tt>Split</tt> method in the <tt>System.String</tt> class to place delimited substrings into a string array.</span></p>
<p><span class="smallblack"><a name="Heading20"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">Parsing strings is not for the faint ofheart. However, the job becomes easier if you have a rich set ofmethods that allow you to perform all types of operations on strings.Substrings are the goal of a majority of these operations, and the <tt>string</tt> class within the .NET Framework contains many methods that are designed to extract or change just a portion of a string.</span></p>
<p><span class="smallblack">The <tt>Substring</tt><i> </i>methodextracts a portion of a string and places it into a new string object.You have two options with this method. If you pass a single integer,the <tt>Substring</tt><i> </i>method extracts the substring thatstarts at that index and continues until it reaches the end of thestring. One thing to keep in mind is that C# array indices are 0 based.The first character within the string will have an index of 0. Thesecond <tt>Substring</tt><i> </i>method accepts an additionalparameter that denotes the ending index. It lets you extract parts of astring in the middle of the string.</span></p>
<p><span class="smallblack">You can create a new character array from a string by using the <tt>ToCharArray</tt><i> </i>method of the <tt>string</tt> class. Furthermore, you can extract a substring from the string and place it into a character array by using the <tt>CopyTo</tt> method. The difference between these two methods is that the character array used with the <tt>CopyTo</tt> method must be an already instantiated array. Whereas the <tt>ToCharArray</tt><i> </i>returns a new character array, the <tt>CopyTo</tt>method expects an existing character array as a parameter to themethod. Furthermore, although methods exist to extract character arraysfrom a string, there is no instance method available to assign acharacter array to a string. To do this, you must create a new stringobject using the <tt>new</tt><i> </i>keyword, as opposed to creatingthe familiar value-type string, and pass the character array as aparameter to the string constructor.</span></p>
<p><span class="smallblack">Using the <tt>Replace</tt><i> </i>method isa powerful way to alter the contents of a string. This method allowsyou to search all instances of a specified substring within a stringand replace those with a different substring. Additionally, the lengthof the substring you want to replace does not have to be the samelength of the string you are replacing it with. If you recall thenumber of times you have performed a search and replace in anyapplication, you can see the possible advantages of this method.</span></p>
<p><span class="smallblack">One other powerful method is <tt>Split</tt>.By passing a character array consisting of delimiter characters, youcan split a string into a group of substrings and place them into astrin</p>
<p>g array. By passing an additional integer parameter, you can alsocontrol how many substrings to extract from the source string.Referring to the code example earlier demonstrating the <tt>Split</tt><i> </i>method, you can split a string representing a directory path into individual directory names by passing the <tt>\</tt>character as the delimiter. You are not, however, confined to using asingle delimiter. If you pass a character array consisting of severaldelimiters, the <tt>Split</tt><i> </i>method extracts substrings based on any of the delimiters that it encounters.</span></p>
<p><span class="smallblack"><a name="Heading21"></a></span></p>
<h2><span class="smallblack">3.7. Using Verbatim String Syntax</span></h2>
<p><span class="smallblack"><b>You want to represent a path to a file using a string without using escape characters for path separators.</b></span></p>
<p><span class="smallblack"><a name="Heading22"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">When assigning a literal string to a string object, preface the string with the <tt>@</tt> symbol. It turns off all escape-character processing so there is no need to escape path separators:</span></p>
<p><span class="smallblack">string nonVerbatim = &quot;C:\Windows\Temp&quot;;<br />string verbatim = @&quot;C:\Windows\Temp&quot;;</span>
<p><span class="smallblack"><a name="Heading23"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">A compiler error that happens so frequently comes from forgetting to escape path separators. Although a common programming <i>faux pas</i>is to include hard-coded path strings, you can overlook that rule whentesting an application. Visual C# .NET added verbatim string syntax asa feature to alleviate the frustration of having to escape all the pathseparators within a file path string, which can be especiallycumbersome for large paths.</span></p>
<p><span class="smallblack"><a name="Heading24"></a></span></p>
<h2><span class="smallblack">3.8. Choosing Between Constant and Mutable Strings</span></h2>
<p><span class="smallblack"><b>You want to choose the correct string data type to best fit your current application design.</b></span></p>
<p><span class="smallblack"><a name="Heading25"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">If you know a string&#39;s value will not change often, use a <tt>string</tt><i> </i>object,which is a constant value. If you need a mutable string, one that canchange its value without having to allocate a new object, use a <tt>StringBuilder</tt>.</span></p>
<p><span class="smallblack"><a name="Heading26"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">Using a regular <tt>string</tt><i> </i>objectis best when you know the string will not change or will only changeslightly. This change includes the whole gamut of string operationsthat change the value of the object itself, such as concatenation,insertion, replacement, or removal of characters. The Common LanguageRuntime (CLR) can use certain properties of strings to optimizeperformance. If the CLR can determine that two string objects are thesame, it can share the memory that these string objects occupy. Thesestrings are then known as <i>interned</i> strings. The CLR contains anintern pool, which is a lookup table of string instances. Strings areautomatically interned if they are assigned to a literal string withincode. However, you can also manually place a string within the internpool by using the <tt>Intern</tt><i> </i>method. To test whether a string is interned, use the <tt>IsInterned</tt> method, as shown in Listing 3.7.</span></p>
<h4><span class="smallblack"> Listing 3.7 Interning a String by Using the <tt>Intern</tt> Method</span></h4>
<p><span class="smallblack">using System;</p>
<p>namespace _7_StringBuilder<br />{<br /> /// &lt;summary&gt;<br /> /// Summary description for Class1.<br /> /// &lt;/summary&gt;<br /> class Class1<br /> {<br /> /// &lt;summary&gt;<br /> /// The main entry point for the application.<br /> /// &lt;/summary&gt;<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> string sLiteral = &quot;Automatically Interned&quot;;<br /> string sNotInterned = &quot;Not &quot; + sLiteral;</p>
<p> TestInterned( sLiteral );<br /> TestInterned( sNotInterned );</p>
<p> String.Intern( sNotInterned );<br /> TestInterned( sNotInterned );<br /> }</p>
<p> static void TestInterned( string str )<br /> {<br /> if( String.IsInterned( str ) != null )<br /> {<br /> Console.WriteLine( &quot;The string \&quot;{0}\&quot; is interned.&quot;, str );<br /> }<br /> else<br /> {<br /> Console.WriteLine( &quot;The string \&quot;{0}\&quot; is not interned.&quot;, str );<br /> }<br /> }<br /> }<br />}</span>
<p><span class="smallblack">A <tt>StringBuilder</tt> behaves similarlyto a regular string object and also contains similar method calls.However, there are no static methods because the <tt>StringBuilder</tt> class is designed to work on string instances. Method calls on an instance of a <tt>StringBuilder</tt><i> </i>object change the internal string of that object, as shown in Listing 3.8. A <tt>StringBuilder</tt>maintains its mutable appearance by creating a buffer that is largeenough to contain a string value and additional memory should thestring need to grow. </span></p>
<h4><span class="smallblack"> Listing 3.8 Manipulating an Internal String Buffer Instead of Returning New String Objects </span></h4>
<p><span class="smallblack">using System;<br />using System.Text;</p>
<p>namespace _7_StringBuilder<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> string string1 = &quot;&quot;;<br /> String string2 = &quot;&quot;;</p>
<p> Console.Write( &quot;Enter string 1: &quot; );<br /> string1 = Console.ReadLine();<br /> Console.Write( &quot;Enter string 2: &quot; );<br /> string2 = Console.ReadLine();</p>
<p> BuildStrings( string1, string2 );<br /> }</p>
<p> public static void BuildStrings( string str1, string str2 )<br /> {<br /> StringBuilder sb = new StringBuilder( str1 + str2 );<br /> sb.Insert( str1.Length, &quot; is the first string.\n&quot; );<br /> sb.Insert( sb.Length, &quot; is the second string.\n&quot; );</p>
<p> Console.WriteLine( sb );<br /> }<br /> }<br />}</span>
<p><span class="smallblack"><a name="Heading27"></a></span></p>
<h2><span class="smallblack">3.9. Optimizing <tt>StringBuilder</tt> Performance</span></h2>
<p><span class="smallblack"><b>Knowing that a </b><tt>StringBuilder</tt><b> object can suffer more of a performance hit than a regular string object, you want to optimize the </b><tt>StringBuilder</tt><b> object to minimize performance issues.</b></span></p>
<p><span class="smallblack"><a name="Heading28"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">Use the <tt>EnsureCapacity</tt><i> </i>method in the <tt>StringBuilder</tt><i> </i>class. Set this integral value to a value that signifies the length of the longest string you may store in this buffer.</span></p>
<p><span class="smallblack"><a name="Heading29"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">The <tt>StringBuilder</tt><i> </i>classcontains methods that allow you to expand the memory of the internalbuffer based on the size of the string you may store. As your stringcontinually grows, the <tt>StringBuilder</tt><i> </i>won&#39;t have torepeatedly allocate new memory for the internal buffer. In other words,if you attempt to place a larger length string than what the internalbuffer of the <tt>StringBuilder</tt> class can accept, then the classwill have to allocate additional memory to accept the new data. If youcontinuously add strings that increase in size from the last inputstring, the <tt>StringBuilder</tt><i> </i>class will have to allocate a new buffer size, which it does internally by calling the <tt>GetStringForStringBuilder</tt> method defined in the <tt>System.String</tt> class. This method ultimately calls the unmanaged method <tt>FastAllocateStrin</p>
<p>g</tt>. By giving the <tt>StringBuilder</tt><i> </i>class a hint using the <tt>EnsureCapacity</tt><i> </i>method, you can help alleviate some of this continual memory reallocation, thereby optimizing the <tt>StringBuilder</tt><i> </i>performance by reducing the amount of memory allocations needed to store a string value.</span></p>
<p><span class="smallblack"><a name="Heading30"></a></span></p>
<h2><span class="smallblack">3.10. Understanding Basic Regular Expression Syntax</span></h2>
<p><span class="smallblack"><b>You want to create a regular expression.</b></span></p>
<p><span class="smallblack"><a name="Heading31"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">Regular expressions consist of a series ofcharacters and quantifiers on those characters. The charactersthemselves can be literal or can be denoted by using character classes,such as <tt>\d</tt>, which denotes a digit character class, or <tt>\S</tt>, which denotes any nonwhitespace character. </span></p>
<h4><span class="smallblack"> Table 3.4 Regular Expression Single Character Classes</span></h4>
<table border="2" cellpadding="2" cellspacing="2">
<colgroup>
<col width="54"></col>
<col width="198"></col>
</colgroup>
<tbody>
<tr valign="TOP">
<td valign="TOP">
<p><b><b>Class</b></b></p>
</td>
<td valign="TOP">
<p><b><b>Description</b></b></p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\d</tt></p>
</td>
<td valign="TOP">
<p>Any digit</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\D</tt></p>
</td>
<td valign="TOP">
<p>Any nondigit</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\w</tt>s</p>
</td>
<td valign="TOP">
<p>Any word character</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\W</tt></p>
</td>
<td valign="TOP">
<p>Any nonword character</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\s</tt></p>
</td>
<td valign="TOP">
<p>Any whitespace character</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\SW</tt></p>
</td>
<td valign="TOP">
<p>Any nonwhitespace</p>
</td>
</tr>
</tbody>
</table>
<p><span class="smallblack"><br /></span></p>
<p><span class="smallblack">Inaddition to the single character classes, you can also specify a rangeor set of characters using ranged and set character classes. Thisability allows you to narrow the search for a specified character bylimiting characters within a specified range or within a defined set.</span></p>
<h4><span class="smallblack"> Table 3.5 Ranged and Set Character Classes</span></h4>
<table border="2" cellpadding="2" cellspacing="2">
<colgroup>
<col width="108"></col>
<col width="334"></col>
</colgroup>
<tbody>
<tr valign="TOP">
<td valign="TOP">
<p><b><b>Format</b></b></p>
</td>
<td valign="TOP">
<p><b><b>Description</b></b></p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>.</tt></p>
</td>
<td valign="TOP">
<p>Any character except newline.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\p{</tt>uc<tt>}</tt></p>
</td>
<td valign="TOP">
<p>Any character within the Unicode character category uc.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>[abcxyz]</tt></p>
</td>
<td valign="TOP">
<p>Any literal character in the set.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\P{uc}</tt></p>
</td>
<td valign="TOP">
<p>Any character not within the Unicode character category uc.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>[^abcxyz]</tt></p>
</td>
<td valign="TOP">
<p>Any character not in the set of literal characters.</p>
</td>
</tr>
</tbody>
</table>
<p><span class="smallblack"><br /></span></p>
<p><span class="smallblack">Quantifierswork on character classes to expand the number of characters thecharacter classes should match. You need to specify, for instance, awildcard character on a character class, which means 0 or morecharacters within that class. Additionally, you can also specify a setnumber of matches of a class that should occur by using an integerwithin braces following the character class designation.</span></p>
<h4><span class="smallblack"> Table 3.6 Character Class Quantifiers</span></h4>
<table border="2" cellpadding="2" cellspacing="2">
<colgroup>
<col width="68"></col>
<col width="189"></col>
</colgroup>
<tbody>
<tr valign="TOP">
<td valign="TOP">
<p><b><b>Format</b></b></p>
</td>
<td valign="TOP">
<p><b><b>Description</b></b></p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>*</tt></p>
</td>
<td valign="TOP">
<p>0 or more characters</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>+</tt></p>
</td>
<td valign="TOP">
<p>1 or more characters</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>?</tt></p>
</td>
<td valign="TOP">
<p>0 or 1 characters</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>{</tt>n<tt>}</tt></p>
</td>
<td valign="TOP">
<p>Exactly n<i> </i>characters</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>{</tt>n,<tt>}</tt></p>
</td>
<td valign="TOP">
<p>At least n<i> </i>characters</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>{</tt>n,m<tt>}</tt></p>
</td>
<td valign="TOP">
<p>At least n<i> </i>but no more than m<i> </i>characters</p>
</td>
</tr>
</tbody>
</table>
<p><span class="smallblack"><br /></span></p>
<p><span class="smallblack">Youcan also specify where a certain regular expression should start withina string. Positional assertions allow you to, for instance, match acertain expression as long as it occurs at the beginning or ending of astring. Furthermore, you can create a regular expression that operateson a set of words within a string by using a positional assertion thatcontinues matching on each subsequent word separated by anynonalphanumeric character.</span></p>
<h4><span class="smallblack"> Table 3.7 Positional (Atomic Zero-Width) Assertions</span></h4>
<table border="2" cellpadding="2" cellspacing="2">
<colgroup>
<col width="63"></col>
<col width="378"></col>
</colgroup>
<tbody>
<tr valign="TOP">
<td valign="TOP">
<p><b><b>Format</b></b></p>
</td>
<td valign="TOP">
<p><b><b>Description</b></b></p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>^</tt></p>
</td>
<td valign="TOP">
<p>Beginning of a string or beginning of a newline</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\z</tt></p>
</td>
<td valign="TOP">
<p>End of the string, including the newline character</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>$</tt></p>
</td>
<td valign="TOP">
<p>End of a string before a newline character or at the end of the line</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\G</tt></p>
</td>
<td valign="TOP">
<p>Continues where the last match left off</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\A</tt></p>
</td>
<td valign="TOP">
<p>Beginning of a string</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\b</tt></p>
</td>
<td valign="TOP">
<p>Between word boundaries (between alphanumeric and nonalphanumeric characters)</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\Z</tt></p>
</td>
<td valign="TOP">
<p>End of the string before the newline character</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\B</tt></p>
</td>
<td valign="TOP">
<p>Characters not between word boundaries</p>
</td>
</tr>
</tbody>
</table>
<p><span class="smallblack"><br /><a name="Heading32"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">Regular expressions use a variety ofcharacters both symbolic and literal to designate how a particularstring of text should be parsed. The act of parsing a string is knownas matching, and when applied to a regular expression, the match willbe either true or false. In other words, when you use a regularexpression to match a series of characters, the match will eithersucceed or fail. As you can see, this process has powerfulapplicability in the area of input validation.</span></p>
<p><span class="smallblack">You build regular expressions using aseries of character classes and quantifiers on those character classesas well as a few miscellaneous regular-expression constructs. You usecharacter classes to match a single character based either on what typeof character it is, such as a digit or letter, or whether it belongswithin a specified range or set of characters (as shown in Table 3.4).Using this information, you can create a series of character classes tomatch a certain string of text. For instance, if you want to specify<br />
aphone number using character classes, you can use the following regularexpression:</span></p>
<p><span class="smallblack">\(\d\d\d\)\s\d\d\d-\d\d\d\d</span>
<p><span class="smallblack">This expression begins by first escapingthe left parenthesis. You must escape it because parentheses are usedfor grouping expressions. Next you can see three digits representing aphone number&#39;s area code followed by the closing parenthesis. You use a<tt>\s</tt> to denote a whitespace character. The remainder of the regular expression contains the remaining digits of the phone number.</span></p>
<p><span class="smallblack">In addition to the single characterclasses, you can also use ranged and set character classes. They giveyou fine-grain control on exactly the type of characters the regularexpression should match. For instance, if you want to match anycharacter as long as it is a vowel, use the following expression:</span></p>
<p><span class="smallblack">[aeiou]</span>
<p><span class="smallblack">This line means that a character shouldmatch one of the literal characters within that set of characters. Aneven more specialized form of single character classes are Unicodecharacter categories. Unicode categories are similar to some of thecharacter-attribute inspection methods shown earlier in this chapter.For instance, you can use Unicode categories to match on uppercase orlowercase characters. Other categories include punctuation characters,currency symbols, and math symbols, to name a few. You can easily findthe full list of Unicode categories in MSDN under the topic &quot;UnicodeCategories Enumeration.&quot;</span></p>
<p><span class="smallblack">You can optimize the phone-number expression, although it&#39;s completely valid, by using <i>quantifiers</i>.Quantifiers specify additional information about the character,character class, or expression to which it applies. Some quantifiersinclude wildcards such as <tt>*</tt>, which means 0 or more occurrences, and <tt>?</tt>,which means only 0 or 1 occurrences of a pattern. You can also usebraces containing an integer to specify how many characters within agiven character class to match. Using this quantifier in thephone-number expression, you can specify that the phone number shouldcontain three digits for the area code followed by three digits andfour digits separated by a dash:</span></p>
<p><span class="smallblack">\(\d{3}\)\s\d{3}-\d{4}</span>
<p><span class="smallblack">Because the regular expression itself isn&#39;tthat complicated, you can still see that using quantifiers can simplifyregular-expression creation. In addition to character classes andquantifiers, you can also use positional information within a regularexpression. For instance, you can specify that given an input string,the regular expression should operate at the beginning of the string.You express it using the <tt>^</tt> character. Likewise, you can also denote the end of a string using the <tt>$</tt>symbol. Take note that this doesn&#39;t mean start at the end of the stringand attempt to make a match because that obviously seemscounterintuitive; no characters exist at the end of the string. Rather,by placing the <tt>$</tt> character following the rest of the regularexpression, it means to match the string with the regular expression aslong as the match occurs at the end of the string. For instance, if youwant to match a sentence in which a phone number is the last portion ofthe sentence, you could use the following:</span></p>
<p><span class="smallblack">\(\d{3}\)\s\d{3}-\d{4}$<br />My phone number is (555) 555-5555 = Match<br />(555) 555-5555 is my phone number = Not a match</span>
<p><span class="smallblack"><a name="Heading33"></a></span></p>
<h2><span class="smallblack">3.11. Validating User Input with Regular Expressions</span></h2>
<p><span class="smallblack"><b>You want to ensure valid user input by using regular expressions to test for validity.</b></span></p>
<p><span class="smallblack"><a name="Heading34"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">Create a <tt>RegEx</tt><i> </i>object, which exists within the <tt>System.Text.RegularExpressions</tt> namespace, passing the regular expression in as a parameter to the constructor. Next, call the member method <tt>Match</tt> using the string you want to validate as a parameter to the method. The method returns a <tt>Match</tt><i> </i>object regardless of the outcome. To test whether a match is made, evaluate the Boolean <tt>Success</tt><i> </i>property on that <tt>Match</tt><i> </i>objectas demonstrated in Listing 3.9. It should also be noted that in manycases, the forward slash (\) character is used when working withregular expressions. To avoid compilation errors from inadvertentlyspecifying an invalid control character, use the <tt>@</tt> symbol to turn off escape processing.</span></p>
<h4><span class="smallblack"> Listing 3.9 Validating User Input of a Phone Number Using a Regular Expression </span></h4>
<p><span class="smallblack">using System;<br />using System.Text.RegularExpressions;</p>
<p>namespace _11_RegularExpressions<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> Regex phoneExp = new Regex( @&quot;^\(\d{3}\)\s\d{3}-\d{4}$&quot; );<br /> string input;</p>
<p> Console.Write( &quot;Enter a phone number: &quot; );<br /> input = Console.ReadLine();</p>
<p> while( phoneExp.Match( input ).Success == false )<br /> {<br /> Console.WriteLine( &quot;Invalid input. Try again.&quot; );<br /> Console.Write( &quot;Enter a phone number: &quot; );<br /> input = Console.ReadLine();<br /> }</p>
<p> Console.WriteLine( &quot;Validated!&quot; );<br /> }<br /> }<br />}</span>
<p><span class="smallblack"><a name="Heading35"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">Earlier in this chapter I mentioned that you could perform data validation using the static methods within the <tt>System.Char</tt><i> </i>class.You can inspect each character within the input string to ensure itmatches exactly what you are looking for. However, this method of inputvalidation can be extremely cumbersome if you have different inputtypes to validate because it requires custom code for each validation.In other words, using the methods in the <tt>System.Char</tt> class is not recommended for anything but the simplest of data-validation procedures.</span></p>
<p><span class="smallblack">Regular expressions, on the other hand,allow you to perform the most advanced input validation possible, allwithin a single expression. You are in effect passing the parsing ofthe input string to the regular-expression engine and offloading allthe work that you would normally do.</span></p>
<p><span class="smallblack">In Listing 3.9, you can see how you createand use a regular expression to test the validity of a phone numberentered by a user. The regular expression is similar to the previousexpressions used earlier for phone numbers except for the addition ofpositional markers. The regular expression is valid if a user enters aphone number and nothing else. A match is successful when the <tt>Success</tt> property within the <tt>Match</tt> object, which is returned from the <tt>Regex.Match</tt><i> </i>method, is <tt>true</tt>.The only caveat to using regular expressions for input validation isthat even though you know the validation failed, you are unable toquery the <tt>Regex</tt><i> </i>or <tt>Match</tt><i> </i>class to see what part of the string failed.</span></p>
<p><span class="smallblack"><a name="Heading36"></a></span></p>
<h2><span class="smallblack">3.12. Replacing Substrings Using Regular Expressions</span></h2>
<p><span class="smallblack"><b>You want to replace all substrings thatmatch a regular expression with a different substring that also usesregular-expression syntax.</b></span></p>
<p><span class="smallblack"><a name="Heading37"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">Create a <tt>Regex</tt><i> </i>object, passing the regular expression used to match characters in the input string to the <tt>Regex</tt><i> </i>constructor. Next,</p>
<p> call the <tt>Regex</tt> method <tt>Replace</tt>,<i> </i>passing the input string to process and the string to replace each match within the input string. You can also use the static <tt>Replace</tt><i> </i>method, passing the regular expression as the first parameter to the method as shown in the last line of Listing 3.10.</span></p>
<h4><span class="smallblack"> Listing 3.10 Using Regular Expressions to Replace Numbers in a Credit Card with xs</span></h4>
<p><span class="smallblack">using System;<br />using System.Text.RegularExpressions;</p>
<p>namespace _12_RegExpReplace<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> Regex cardExp = new Regex( @&quot;(\d{4})-(\d{4})-(\d{4})-(\d{4})&quot; );<br /> string safeOutputExp = &quot;$1-xxxx-xxxx-$4&quot;;<br /> string cardNum;</p>
<p> Console.Write( &quot;Please enter your credit card number: &quot; );<br /> cardNum = Console.ReadLine();</p>
<p> while( cardExp.Match( cardNum ).Success == false )<br /> {<br /> Console.WriteLine( &quot;Invalid card number. Try again.&quot; );<br /> Console.Write( &quot;Please enter your credit card number: &quot; );</p>
<p> cardNum = Console.ReadLine();<br /> }</p>
<p> Console.WriteLine( &quot;Secure Output Result = {0}&quot;, <br /> cardExp.Replace( cardNum, safeOutputExp ));<br /> }<br /> }<br />}</span>
<p><span class="smallblack"><a name="Heading38"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">Although input validation is an extremelyuseful feature of regular expressions, they also work well as textparsers. The previous recipe used regular expressions to verify that aparticular string matched a regular expression exactly. However, youcan also use regular expressions to match substrings within a stringand return each of those substrings as a group. Furthermore, you canuse a separate regular expression that acts on the result of theregular-expression evaluation to replace substrings within the originalinput string. </span></p>
<p><span class="smallblack">Listing 3.10 creates a regular expressionthat matches the format for a credit card. In that regular expression,you can see that it will match on four different groups of four digitsapiece separated by a dash. However, you might also notice that eachone of these groups is surrounded with parentheses. In an earlierrecipe, I mentioned that to use a literal parenthesis, you must escapeit using a backslash because of the conflict with regular-expressiongrouping symbols. In this case, you want to use the grouping feature ofregular expressions. When you place a portion of a regular expressionwithin parentheses, you are creating a numbered group. Groups arenumbered starting with 1 and are incremented for each subsequent group.In this case, there are four numbered groups. These groups are used bythe replacement string, which is contained in the string <tt>safeOutputExp</tt>. To reference a numbered group, use the <tt>$</tt>symbol followed by the number of the group to reference. This sequencerepresents all characters within the input string that match the groupexpression within the regular expression. Therefore, in the replacementstring, you can see that it prints the characters within the firstgroup, replaces the characters in the second and third groups with xs,and finally prints the characters in the fourth group.</span></p>
<p><span class="smallblack">One thing to note is that you can use the <tt>RegEx</tt><i> </i>class to view the groups themselves. If you change the regular expression to &quot;<tt>\d{4}</tt>&quot;, you can then use the <tt>Matches</tt><i> </i>method to enumerate all the groups using the <tt>foreach</tt><i> </i>keyword,as shown in Listing 3.11. In the listing, the program first checks tomake sure at least four matches were made. This number corresponds tofour groups of four digits. Next, it uses a <tt>foreach</tt><i> </i>enumeration on each <tt>Match</tt> object that is returned from the <tt>Matches</tt><i> </i>method. If the match is in the second or third group, the values are replaced with xs; otherwise, the <tt>Match</tt><i> </i>object&#39;s value, the characters within that group, are concatenated to the result string.</span></p>
<h4><span class="smallblack"> Listing 3.11 Enumerating Through the <tt>Match</tt> Collection to Perform Special Operations on Each Match in a Regular Expression </span></h4>
<p><span class="smallblack">static void TestManualGrouping()<br />{<br /> Regex cardExp = new Regex( @&quot;\d{4}&quot; );<br /> string cardNum;<br /> string safeOutputExp = &quot;&quot;;</p>
<p> Console.Write( &quot;Please enter your credit card number: &quot; );<br /> cardNum = Console.ReadLine();</p>
<p> if( cardExp.Matches( cardNum ).Count &lt; 4 )<br /> {<br /> Console.WriteLine( &quot;Invalid card number&quot; );<br /> return;<br /> }</p>
<p> foreach( Match field in cardExp.Matches( cardNum ))<br /> {<br /> if( field.Success == false )<br /> {<br /> Console.WriteLine( &quot;Invalid card number&quot; );<br /> return;<br /> }</p>
<p> if( field.Index == 5 || field.Index == 10 )<br /> {<br /> safeOutputExp += &quot;-xxxx-&quot;;<br /> }<br /> else<br /> {<br /> safeOutputExp += field.Value;<br /> }<br /> }</p>
<p> Console.WriteLine( &quot;Secure Output Result = {0}&quot;, safeOutputExp );<br />}</span>
<p><span class="smallblack"><a name="Heading39"></a></span></p>
<h2><span class="smallblack">3.13. Building a Regular Expression Library</span></h2>
<p><span class="smallblack"><b>You want to create a library of regular expressions that you can reuse in other projects.</b></span></p>
<p><span class="smallblack"><a name="Heading40"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">Use the <tt>CompileToAssembly</tt><i> </i>static method within the <tt>Regex</tt><i> </i>class to compile a regular expression into an assembly. This method uses an array of <tt>RegexCompilationInfo</tt><i> </i>objects that contain any number of regular expressions you want to add to the assembly.</span></p>
<p><span class="smallblack">The <tt>RegexCompilationInfo</tt><i> </i>classcontains a constructor with five fields that you must fill out. Theparameters denote the string for the regular expression; any optionsfor the regular expression, which appear in the <tt>RegexOptions</tt>enumerated type; a name for the class that is created to hold theregular expression; a corresponding namespace; and a Boolean valuespecifying whether the created class should have a public accessmodifier.</span></p>
<p><span class="smallblack">After creating the <tt>RegexCompilationInfo</tt> object, create an <tt>AssemblyName</tt><i> </i>object, making sure to reference the <tt>System.Reflection</tt><i> </i>namespace, and set the <tt>Name</tt><i> </i>property to a name you want the resultant assembly filename to be. Because the <tt>CompileToAssembly</tt><i> </i>creates a DLL, exclude the DLL extension on the assembly name. Finally, place all the <tt>RegexCompilationInfo</tt><i> </i>objects within an array, as shown in Listing 3.12, and call the <tt>CompileToAssembly</tt><i> </i>method. Listing 3.12 demonstrates how to create a <tt>RegexCompilationInfo</tt><i> </i>object and how to use that object to compile a regular expression into an assembly using the <tt>CompileToAssembly</tt> method.</span></p>
<h4><span class="smallblack"> Listing 3.12 Using the <tt>CompileToAssembly</tt> <tt>Regex</tt> Method to Save Regular Expressions in a New Assembly for Later Reuse </span></h4>
<p><span class="smallblack">using System;<br />using System.Text.RegularExpressions;<br />using System.Reflection;</p>
<p>namespace _12_RegExpReplace<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> CompileRegex(@&quot;(\d{4})-(\d{4})-(\d{4})-(\d{4})&quot;, @&quot;regexlib&quot; );<br /> }</p>
<p> static void CompileRegex( string exp, string assemblyName )<br /> {<br /> RegexCompilationInfo compInfo = <br /> new RegexCompilationInfo( exp, 0, &quot;CreditCardExp&quot;, &quot;&quot;, true );<br /> AssemblyName assembly = new AssemblyName();<br /> ass</p>
<p>embly.Name = assemblyName;</p>
<p> RegexCompilationInfo[] rciArray = { compInfo };</p>
<p> Regex.CompileToAssembly( rciArray, assembly );<br /> }<br /> }<br />}</span>
<p><span class="smallblack"><a name="Heading41"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">If you use regular expressions regularly,then you might find it advantageous to create a reusable library of theexpressions you tend to use the most. The <tt>Regex</tt><i> </i>class contains a method named <tt>CompileToAssembly</tt> that allows you to compile several regular expressions into an assembly that you can then reference within other projects.</span></p>
<p><span class="smallblack">Internally, you will find a class for eachregular expression you added, all contained within its correspondingnamespace, as specified in the <tt>RegexCompilationInfo</tt><i> </i>object when you created it. Furthermore, each of these classes inherits from the <tt>Regex</tt><i> </i>class so all the <tt>Regex</tt><i> </i>methodsare available for you to use. As you can see, creating a library ofcommonly used regular expressions allows you to reuse and share theseexpressions in a multitude of different projects. A change in a regularexpression simply involves changing one assembly instead of eachproject that hard-coded the regular expression.</span></p>
<p><span class="smallblack"><br /></span></p>
<p class="navigation"><span class="smallblack">&copy; Copyright Pearson Education. All rights reserved.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2007/05/c-strings-and-regular-expressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# String Type Object Peculiarities</title>
		<link>http://www.csharphelp.com/2007/03/c-string-type-object-peculiarities/</link>
		<comments>http://www.csharphelp.com/2007/03/c-string-type-object-peculiarities/#comments</comments>
		<pubDate>Mon, 19 Mar 2007 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Strings]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=487</guid>
		<description><![CDATA[Purpose The main purpose of this article is to exploresome common and uncommon issues regarding DotNet and C#. Among suchcommon things my first article is on string data type which isreference type but some developers don?t understand it?s behavior whencompare with others reference type. Problem Changing the value of an alias reflect the change in [...]]]></description>
			<content:encoded><![CDATA[<p><span class="smallblack"><b>Purpose</b></span></p>
<p><span class="smallblack">The main purpose of this article is to exploresome common and uncommon issues regarding DotNet and C#. Among suchcommon things my first article is on string data type which isreference type but some developers don?t understand it?s behavior whencompare with others reference type.</span></p>
<p><span class="smallblack"><b>Problem</b></span></p>
<p><span class="smallblack">Changing the value of an alias reflect the change in the actual class object and vice versa.</span></p>
<p><span class="smallblack"><b>Explanation</b></span></p>
<p><span class="smallblack"><b>Reference Type</b></span></p>
<p><span class="smallblack">Let assume that we have a class called MyType.There is another class called AppType. MyType has a property calledName. AppType is simply used to run the application by providing Mainmethod.</span></p>
<p><span class="smallblack">Here, is the code</span></p>
<p><span class="smallblack">//Program#1</p>
<p>using System;<br />using System.Console;<br />class MyType<br />{<br /> private string name;<br /> private string Name<br /> { set<br /> {<br /> name=value;<br /> }<br /> get<br /> {<br /> return name;<br /> }<br /> }<br />}</p>
<p>class AppType<br />{<br /> public static void Main()<br /> {<br /> MyType obj1,obj2;<br /> Console.WriteLine(&quot;*****Learning reference philosophy*****&quot;);<br /> obj2=new MyType();<br /> obj2.Name=&quot;Sadiq&quot;;<br /> obj1=obj2;<br /> Console.WriteLine(&quot;values of obj1={0} and obj2={1}&quot;,obj1.Name,obj2.Name);<br /> obj1.Name=&quot;Ahmed&quot;;<br /> Console.WriteLine(&quot;values of obj1={0} and obj2={1}&quot;,obj1.Name,obj2.Name);<br /> }<br />}<br /></span>
<p><span class="smallblack">when you compile the code, you?ll get the following output</span></p>
<p><span class="smallblack"> *****Learning reference philosophy*****</span></p>
<p><span class="smallblack">values of obj1=Sadiq and obj2=Sadiq</span></p>
<p><span class="smallblack">values of obj1=Ahmed and obj2=Ahmed</span></p>
<p><span class="smallblack">It means that object obj1 is nothing exceptthe alias of obj2.In other words, both obj1 and obj2 are pointing tothe same memory.</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives3/files/archive505/image002.jpg" alt="" /></span></p>
<p><span class="smallblack"><b>Value Type</b></span></p>
<p><span class="smallblack">Let assume that we have a structure calledMyType. There is another structure called AppType. MyType has aproperty called Name. AppType is simply used to run the application byproviding Main method.</span></p>
<p><span class="smallblack">Here, is the code</span></p>
<p><span class="smallblack">//Program#2<br />using System;<br />using System.Console;<br />class MyType<br />{<br /> private string name;<br /> private string Name<br /> { set<br /> {<br /> name=value;<br /> }<br /> get<br /> {<br /> return name;<br /> }<br /> }<br />}</p>
<p>class AppType<br />{<br /> public static void Main()<br /> {<br /> MyType obj1,obj2;<br /> Console.WriteLine(&quot;*****Learning reference philosophy*****&quot;);<br /> obj2=new MyType();<br /> obj2.Name=&quot;Sadiq&quot;;<br /> obj1=obj2;<br /> Console.WriteLine(&quot;values of obj1={0} and obj2={1}&quot;,obj1.Name,obj2.Name);<br /> obj1.Name=&quot;Ahmed&quot;;<br /> Console.WriteLine(&quot;values of obj1={0} and obj2={1}&quot;,obj1.Name,obj2.Name);<br /> }<br />}<br /></span>
<p><span class="smallblack">when you compile the code, you?ll get the following output</span></p>
<p><span class="smallblack">*****Learning reference philosophy*****</span></p>
<p><span class="smallblack">values of obj1=Sadiq and obj2=Sadiq</span></p>
<p><span class="smallblack">values of obj1=Ahmed and obj2=Sadiq</span></p>
<p><span class="smallblack">It means that object obj1 and obj2 both aredifferent .In other words, both obj1 and obj2 are distinct and pointingto the different memory.</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives3/files/archive505/image004.jpg" alt="" /></span></p>
<p><span class="smallblack"><b>Reference or Value type</b></span></p>
<p><span class="smallblack">Now, consider String type instead of user defined data type. The above code will become,</span></p>
<p><span class="smallblack">//Program#3<br />class AppType<br />{<br /> public static void Main()<br /> {<br /> String obj1,obj2;<br /> Console.WriteLine(&quot;*****Learning reference philosophy*****&quot;);<br /> //No need of it<br /> //obj2=new MyType();<br /> obj2=&quot;Sadiq&quot;;<br /> obj1=obj2;<br /> Console. WriteLine(&quot;values of obj1={0} and obj2={1}&quot;,obj1,obj2);<br /> obj1=&quot;Ahmed&quot;;<br /> Console.WriteLine(&quot;values of obj1={0} and obj2={1}&quot;,obj1,obj2);<br /> }<br />}<br /></span>
<p><span class="smallblack">when you compile the code, you?ll get the following output </span></p>
<p><span class="smallblack">*****Learning reference philosophy*****</span></p>
<p><span class="smallblack">values of obj1=Sadiq and obj2=Sadiq</span></p>
<p><span class="smallblack">values of obj1=Ahmed and obj2=Sadiq</span></p>
<p><span class="smallblack">It means that object obj1 is not an alias of obj2.In other words, both obj1 and obj2 are pointing to the different memory.</span></p>
<p><span class="smallblack">Strange!</span></p>
<p><span class="smallblack">Now, we all know that String type objectdynamically grow. It implies that it must allocate its memory on theHeap. Since, reference type allocates the memory on Heap, therefore, itshould be reference type. </span></p>
<p><span class="smallblack">If it is reference type than why it behaves as value type.</span></p>
<p><span class="smallblack"><b>Reason</b></span></p>
<p><span class="smallblack">The fact lies in these following two lines,<br />string obj1;</span></p>
<p><span class="smallblack">obj1 = ?value forces to allocate a memory?;</span></p>
<p><span class="smallblack">The first line is nothing except thedeclaration of an object while second line actually creates the object.It means that you can conceptually relate second line to </span></p>
<p><span class="smallblack">obj=new string();.</span></p>
<p><span class="smallblack"><b>Summary</b></span></p>
<p><span class="smallblack">Therefore, whenever the value of a string object initialized or assigned it creates an object in memory. </span></p>
<p><span class="smallblack">Now, we It means that object obj1 is not analias of obj2.In other words, both obj1 and obj2 are pointing to thedifferent memory.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2007/03/c-string-type-object-peculiarities/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Manipulating Strings The Way C/C++ Programmers Use To</title>
		<link>http://www.csharphelp.com/2006/11/manipulating-strings-the-way-cc-programmers-use-to/</link>
		<comments>http://www.csharphelp.com/2006/11/manipulating-strings-the-way-cc-programmers-use-to/#comments</comments>
		<pubDate>Mon, 06 Nov 2006 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Strings]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=354</guid>
		<description><![CDATA[I have been asked a lot lately, how come it&#39;sso different in C# to play around with strings? How come we have to doso many manipulations. We used to do this using recursions. Whilerecursions are fine, they are a main source for flaws and glitches, andI don&#39;t think you have to use them. In this [...]]]></description>
			<content:encoded><![CDATA[<p><span class="smallblack">I have been asked a lot lately, how come it&#39;sso different in C# to play around with strings? How come we have to doso many manipulations. We used to do this using recursions. Whilerecursions are fine, they are a main source for flaws and glitches, andI don&#39;t think you have to use them.</span></p>
<p><span class="smallblack">In this article U will show you couple of tricks that will make the transitition to C# from C/C++ easier.</span></p>
<p><span class="smallblack">Let&#39;s start with a simple C++ code to reverse a string:</span></p>
<p><span class="smallestblack"><span class="smallblack">int Reverse(char* str)<br />{</p>
<p>if (NULL==str)return -1; //no string<br />int l=strlen(str)-1; //get the string length<br />if (1==l)return 1;</p>
<p>for(int x=0;x &lt; l;x++,l&#8211;)<br />{<br />str[x]^=str[l]; //triple XOR Trick<br />str[l]^=str[x]; //for not using a temp<br />str[x]^=str[l];<br />}</p>
<p>return 0;</p>
<p>}<br /></span>
<p><span class="smallblack">That is easy right? We want to accomplish the same without any recursion needed.</span></p>
<p><span class="smallblack">Here is how it is done using recursion in c#:</span></p>
<p><span class="smallestblack"><span class="smallblack">public static string Reverse(string str) <br />{ <br />	/*termination condition*/<br />	 if(1==str.Length) <br />	{ <br />		return str; <br />	} <br />	else <br />	{ <br />		return Reverse( str.Substring(1) ) + str.Substring(0,1); <br />	} <br />} <br /> </span>
<p><span class="smallblack">While the C# recursion version looks smart andeasy enough, it&#39;s hard for some of us to keep track of what is going oninside, and you know what .. it might just look a lot smarter to usethe old pointer-like string manipulations.</span></p>
<p><span class="smallblack">This C# version of the same reverse functionuses the string.Substring method for getting a char[] array of thestring representation, after playing with the char array (we couldsearch it, cut/inside, and normally everything we did in C++ chararrays) we will convert it to a C# string back to the user:</span></p>
<p><span class="smallestblack"><span class="smallblack">private string Rev(string str)<br />{ <br />	char[] c = str.ToCharArray (); /*convert to chararray*/ <br />	int l = str.Length -1; </p>
<p>	if (1==l)return str; //no need to reverse.</p>
<p>	for (int j=0;j &lt; l;j++,l&#8211;) <br />	 { <br />		c[j]^=c[l]; /*triple xor will */ <br /> c[l]^=c[j]; /*replace c[j] with c[i]*/ <br />		c[j]^=c[l]; /*without a temp var*/ <br />	 } </p>
<p>	string s=new string(c); /*convert back to string*/ <br />	return s;<br />}<br /></span>
<p><span class="smallblack">You can see here, that after converting thestring to a char array, basically we are doing much of the C++ codingstyles we used to. We are promised by .NET that the string x that isprovided will not be NULL, and so we are guaranteed to not fall forthat here.</span></p>
<p><span class="smallblack">Let&#39;s have one more.</span></p>
<p><span class="smallblack">There is an old interview question in C++ thatgoes like: &quot;implement the atoi STL function (the function that gets achar* that represent (or not) a number and returns an integer&quot;.</span></p>
<p><span class="smallblack">In C++ the code might look like:</span></p>
<p><span class="smallestblack"><span class="smallblack">int atoi(char* str)<br />{<br />int sign=1;<br />int x=0; //counter<br />if (NULL==str)return 0; //might confuse</p>
<p>if (&#39;-&#39;==str[0]){sign=-1; x=1;}</p>
<p>int TheNumber=0;<br />int tmp;</p>
<p>int l=strlen(str)-1;</p>
<p> for(;x &lt;= l;x++)<br /> {<br /> if ((str[x]&gt;=&#39;0&#39;)&amp;&amp;(str[x]&lt;=&#39;9&#39;))<br />	{<br />	tmp=(str[x]-&#39;0&#39;);//0 is the 0 index<br />	TheNumber=TheNumber*10+tmp; //to enlarge the number by *10 every time<br />	}<br /> }</p>
<p>TheNumber*=sign;</p>
<p>return TheNumber;<br />}<br /></span>
<p><span class="smallblack">In this example, the string &quot;12mn4&quot; willproduce 124 as a result, meaning &#8211; coming across a non-number char willnot break the loop.</span></p>
<p><span class="smallblack">To look really bad, the same code could be writen in C# like this:</span></p>
<p><span class="smallestblack"><span class="smallblack">public static int atoi(string str)<br />{<br /> return int.Parse(str);<br />}<br /></span>
<p><span class="smallblack">To look smarter in a C# interview, you might wanna consider writing it like so:</span></p>
<p><span class="smallestblack"><span class="smallblack">public static int atoi(string str)<br />{<br />int sign=1;<br />int TheNumber=0;<br />int tmp=0;<br />int x=0;<br />int l=(str.Length)-1;<br />char[] c=str.ToCharArray();</p>
<p>if (&#39;-&#39;==c[0]){sign=-1; x=1;}</p>
<p> for(;x &lt; l;x++)<br /> {<br /> if ((c[x]&gt;=&#39;0&#39;)&amp;&amp;(c[x]&lt;=&#39;9&#39;))<br />	{<br />	tmp=(c[x]-&#39;0&#39;);//0 is the 0 index<br />	TheNumber=TheNumber*10+tmp; //to enlarge the number by *10 every time<br />	}<br /> }</p>
<p>return TheNumber*sign;</p>
<p>}<br /></span>
<p><span class="smallblack">Pretty much the same ha?</span></p>
<p><span class="smallblack">Conclusion:<br />If you like C++ and find the string jargon annoying while moving to C#, use ToCharArray.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2006/11/manipulating-strings-the-way-cc-programmers-use-to/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XML String Building</title>
		<link>http://www.csharphelp.com/2006/08/xml-string-building/</link>
		<comments>http://www.csharphelp.com/2006/08/xml-string-building/#comments</comments>
		<pubDate>Fri, 25 Aug 2006 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Strings]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=281</guid>
		<description><![CDATA[How to build XML string with only changed rows/columns edit on user form? Formerly I&#39;ve been working on three-tier applications on J2EE platform. All aplication logic was written in EJB and all the data was send as XML string from PowerBuilder clients. I was thinking how to implement such kind of solution in .NET through [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-size:xx-small;"><b><br /></b></span><span class="smallblack"><a href="mailto:Damjan.Kovac@mobitel.si"></a></span></p>
<p><span class="smallblack">How to build XML string with only changed rows/columns edit on user form?</span></p>
<p><span class="smallblack">Formerly I&#39;ve been working on three-tier applications on J2EE platform. All aplication logic was written in EJB and all the data was send as XML string from PowerBuilder clients. I was thinking how to implement such kind of solution in .NET through ADO.NET. The most simple way is to send data as DataSet object which also includes XMLrepresetation of containing data objects (datatables, datacolumns, etc.). But sending the whole dataset has too much overhead. We only want to send changed/modified data to middle-tier .NET component. How to do this in aefficient manner?</span></p>
<p><span class="smallblack"> The basic idea is to send only changed rows/columns of DataTable object. The method below takes two parameters:- DataTable table: only changed rows from input form/datagrid<br />- string keyColName: name of key column of table</span></p>
<p><span class="smallblack">We use three different statuses for row tag:<br />- &quot;INSERT&quot;: new added row<br />- &quot;UPDATE&quot;: updated row<br />- &quot;DELETE&quot;: deleted row<br /></span></p>
<p><span class="smallestblack"><span class="smallblack">/// &lt;summary&gt;<br />/// Returns XML string of changed DataTable rows<br />/// &lt;/summary&gt;<br />public string GetXML(DataTable table, string keyColName) {<br /> DataView ldvOriginal = new DataView(table);<br /> DataView ldvChanged = new DataView(table);<br /> DataView ldvAdded = new DataView(table);<br /> DataView ldvDeleted = new DataView(table);<br /> ldvOriginal.RowStateFilter = DataViewRowState.ModifiedOriginal;<br /> ldvChanged.RowStateFilter = DataViewRowState.ModifiedCurrent;<br /> ldvAdded.RowStateFilter = DataViewRowState.Added;<br /> ldvDeleted.RowStateFilter = DataViewRowState.Deleted;</p>
<p> string lsXml = &quot;&lt;?xml version=\&quot;1.0\&quot;?&gt;\n&quot;;<br /> string lsStatusInsert = &quot;&lt;row status=\&quot;INSERT\&quot;&gt;\n&quot;;<br /> string lsStatusUpdate = &quot;&lt;row status=\&quot;UPDATE\&quot;&gt;\n&quot;;<br /> string lsStatusDelete = &quot;&lt;row status=\&quot;DELETE\&quot;&gt;\n&quot;;<br /> int noAdded = ldvAdded.Count;<br /> int noChanged = ldvChanged.Count;<br /> int noDeleted = ldvDeleted.Count;</p>
<p> try {<br /> // added rows<br /> lsXml += &quot;&lt;&quot; + table.TableName + &quot;&gt;\n&quot;;<br /> for (int i=0; i &lt; noAdded; i++) {<br /> lsXml += lsStatusInsert;<br /> foreach (DataColumn dc in ldvAdded.Table.Columns) {<br /> if (ldvAdded[i][dc.ColumnName].ToString().Length &gt; 0)<br /> lsXml += &quot;&lt;&quot; + dc.ColumnName + &quot;&gt;&quot; +<br /> ldvAdded[i][dc.ColumnName] +<br /> &quot;&lt;&quot; + dc.ColumnName + &quot;&gt;\n&quot;;<br /> } // foreach column<br /> lsXml += &quot;&lt;/row&gt;\n&quot;;<br /> } // for<br /> // modified rows<br /> for (int i=0; i &lt; noChanged; i++) {<br /> lsXml += lsStatusUpdate;<br /> foreach (DataColumn dc in ldvChanged.Table.Columns) {<br /> if (keyColName.Equals(dc.ColumnName))<br /> lsXml += &quot;&lt;&quot; + dc.ColumnName + &quot;&gt;&quot; +<br /> ldvChanged[i][dc.ColumnName] +<br /> &quot;&lt;&quot; + dc.ColumnName + &quot;&gt;\n&quot;;<br /> else<br /> if (!ldvOriginal[i][dc.ColumnName].ToString().Equals(ldvChanged[i][dc.ColumnName].ToString()))<br /> lsXml += &quot;&lt;&quot; + dc.ColumnName + &quot;&gt;&quot; +<br /> ldvChanged[i][dc.ColumnName] +<br /> &quot;&lt;&quot; + dc.ColumnName + &quot;&gt;\n&quot;;<br /> } // foreach column<br /> lsXml += &quot;&lt;/row&gt;\n&quot;;<br /> } // for <br /> // deleted rows<br /> for (int i=0; i &lt; noDeleted; i++) {<br /> lsXml += lsStatusDelete;<br /> lsXml += &quot;&lt;&quot; + keyColName + &quot;&gt;&quot; + ldvDeleted[i][keyColName] + &quot;&lt;&quot; + keyColName + &quot;&gt;\n&quot;; <br /> lsXml += &quot;&lt;/row&gt;\n&quot;;<br /> } // for <br /> lsXml += &quot;&lt;&quot; + table.TableName + &quot;&gt;\n&quot;;</p>
<p> } catch (Exception ex) {<br /> throw ex;<br /> }<br /> return lsXml;<br />}<br /></span>
<p><span class="smallblack">&#8230;</span></p>
<p><span class="smallblack">Example:<br /></span></p>
<p><span class="smallestblack"><span class="smallblack">DataTable dt = new DataTable(&quot;DemoTable&quot;);<br />// we fill this table through DataAdapter Fill() method <br />// and we edit data in user control such as DataGrid, form,..<br />..</p>
<p>if (dt.GetChanges()!=null) {<br /> string xml = this.GetXML(dt.GetChanges(), &quot;customer_id&quot;);<br /> // pass xml to middle-tier..</p>
<p>}<br /></span>
<p><span class="smallblack">Method returns XML string which can be passed to middle tier. Here we parse it and do all necessary bussiness logic due to row status. We do not need XSD because we can get metadata in the middle tier component directly from database table. </span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2006/08/xml-string-building/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>String To A Byte Array</title>
		<link>http://www.csharphelp.com/2006/08/string-to-a-byte-array/</link>
		<comments>http://www.csharphelp.com/2006/08/string-to-a-byte-array/#comments</comments>
		<pubDate>Wed, 23 Aug 2006 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Strings]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=279</guid>
		<description><![CDATA[&#160; preamble this simple function converts a string to a byte[] that is in compliant with the visual c++ 6.0 BSTR/WCHAR. why might you want to use it? well for a start, for data compatability with those all programs you laboured over. Another reason I use it is for eventlogging. The EventLog class has an [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-size:xx-small;"><b><br /></b></span><span class="smallblack"><a href="mailto:david@thebigword.com"></a></span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><strong>preamble</strong></span></p>
<p><span class="smallblack">this simple function converts a string to a byte[] that is in compliant with the visual c++ 6.0 BSTR/WCHAR.</span></p>
<p><span class="smallblack">why might you want to use it?</span></p>
<p><span class="smallblack">well for a start, for data compatability with those all programs you laboured over. </span></p>
<p><span class="smallblack">Another reason I use it is for eventlogging.</span></p>
<p><span class="smallblack">The <strong>EventLog</strong> class has an overloaded member function (WriteEntry) that allows you to end a byte array as the data for an event:<span style="color:#0000ff;">public void</span> <strong>WriteEntry</strong>(<span style="color:#0000ff;">string</span> message, EventLogEntryType type, <span style="color:#0000ff;">int</span> eventID, <span style="color:#0000ff;">short</span> category, <span style="color:#0000ff;">byte</span>[] rawData);</span></p>
<p><span class="smallblack">The value you pass as <em>rawData </em>appears in the Data pane when you view the Event\;s properties in the system\;s Event Viewer, thus:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives2/files/archive292/image1.gif" alt="" /></span></p>
<p><span class="smallblack"><b>figure 1</b> the data pane in the event properties</span></p>
<p><span class="smallblack">As you can see, the data pane provide an invaluable way of providing extra debugging information.</span></p>
<p><span class="smallblack"><strong>function declaration</strong></span></p>
<p><code></code></p>
<p><span class="smallblack"><span style="color:#0000ff;">protected internal void</span> StringToByteArray(<span style="color:#0000ff;">string</span> theString, <span style="color:#0000ff;">ref byte</span>[] data, <span style="color:#0000ff;">int</span> offset)&nbsp;<br />{ <br />&nbsp;&nbsp;&nbsp; <span style="color:#0000ff;">int</span> realI = 0; <br />&nbsp;&nbsp;&nbsp; for(<span style="color:#0000ff;">int</span> i = 0; i &lt; theString.Length; ++i) <br />&nbsp;&nbsp;&nbsp; { <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; realI = (i*2) + offset;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; data[realI] = (<span style="color:#0000ff;">byte</span>)(theString[i] &amp; 0xFF);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; data[realI + 1] = (<span style="color:#0000ff;">byte</span>)((theString[i] &amp; 0xFF00) &gt;&gt; 16); <br />&nbsp;&nbsp;&nbsp; } <br />}</span></p>
<p><span class="smallblack"><strong>notes</strong></span></p>
<p><span class="smallblack">the first thing to note is that no error checking occurs and that it\;s therefore very probable that exceptions will be thrown if the byte[] isn\;t big enough.</span></p>
<p><span class="smallblack">the <em>offset </em>parameter allows you to specify an offset,&nbsp;in bytes, from the start of the <em>data</em> array, to start copying into. It is important to realise that this is in bytes, as each element of a <span style="color:#0000ff;">string</span> is two bytes long. </span></p>
<p><span class="smallblack"><strong>example</strong></span></p>
<p><span class="smallblack"><span style="color:#0000ff;">string</span> firstName = &quot;Bill&quot;;<br /><span style="color:#0000ff;">string</span> surname = &quot;Gates&quot;;</span></p>
<p><span class="smallblack"><span style="color:#008000;">//for compatability with vc++6, remember to pad each string with two zero bytes at the end.<br />//also, as we\;re putting a space in the middle of the string, we need to add an extra two bytes.</span><br /><span style="color:#0000ff;">byte</span>[] bData&nbsp;= <span style="color:#0000ff;">new byte</span>[(firstName.Length + surname.Length) * 2 + 4] ;</span></p>
<p><span class="smallblack">StringToByteArray(firstName + &quot; &quot;, <span style="color:#0000ff;">ref</span> bData, 0); <span style="color:#008000;">//copies firstName into the bData array<br /></span><br />StringToByteArray(surname, <span style="color:#0000ff;">ref</span> bData,&nbsp; (firstName.Length * 2) + 2); <br /><span style="color:#008000;">//remember, each element in a string is two bytes long, and the space we added abve will count as an extra 2 bytes.</span></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2006/08/string-to-a-byte-array/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>String extractors and manipulators in C# &#8211; Part IV</title>
		<link>http://www.csharphelp.com/2006/04/string-extractors-and-manipulators-in-c-part-iv/</link>
		<comments>http://www.csharphelp.com/2006/04/string-extractors-and-manipulators-in-c-part-iv/#comments</comments>
		<pubDate>Sat, 15 Apr 2006 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Strings]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=149</guid>
		<description><![CDATA[The &#34;toupper&#34; and &#34;tolower&#34; methods, in thefollowing class, are both similar except for the one line conversion ofthe &#39;int&#39; type data member ucode, which represents the ASCII value ofthe character read from the string or keyboard, to lowercase oruppercase. After determining the length of the string passed to it,both the methods scan each character in [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-size:xx-small;"><b><br /></b></span><span class="smallblack"><a href="http://www.csharphelp.com/bio/jv.html"></a></span></p>
<p><span class="smallblack">The &quot;toupper&quot; and &quot;tolower&quot; methods, in thefollowing class, are both similar except for the one line conversion ofthe &#39;int&#39; type data member ucode, which represents the ASCII value ofthe character read from the string or keyboard, to lowercase oruppercase. After determining the length of the string passed to it,both the methods scan each character in the string into a &#39;char&#39; typedata member and then convert the character to the opposite case afterevaluating the case in an if&#8230;else block. Quite simple ! And thissimplicity is because of the indexer of the class provided by C#, whichallows for each character in the string to be scanned as if from anarray of strings ! Both methods return objects and receive objectshence are defined of type object. </span></p>
<p><span class="smallblack">The following is the class which converts characters in a string into uppercase or lowercase</span></p>
<p><span class="smallblack">using system;</p>
<p>class convertstr<br />{<br /> private string s1; // The string type data member which is used to return the<br /> // converted string<br /> private int ucode; // The int type data member which is used to <br /> public string toupper(string s2) // The toupper method returning a string object<br /> {<br /> public int strlen=s2.Length; // Determines the string length for the &#39;for&#39; loop<br /> for (int i=0;i &lt; strlen;i++) // Reads each character in string via the indexer<br /> {<br /> char ch=s2[i];<br /> if (ch &gt; =&#39;a&#39; &amp;&amp; ch &lt; =&#39;z&#39;) // Determines if the character is an alphabet and in { <br /> // lower case<br /> ucode=(int)ch;<br /> ucode=ucode-32; <br /> s1[i]=(char)ucode;<br /> }<br /> else // else retains the same case into the string object of { <br /> // the class<br /> s1[i]=ch;<br /> }<br /> }<br /> return s1; // Method returns converted string<br /> }<br /> public string tolower(string s4) // The tolower method returning a string object<br /> {<br /> public int strlen=s4.Length;<br /> for (int i=0;i &lt; strlen;i++) // Reads each character in string via the indexer<br /> {<br /> char ch=s4[i];<br /> if (ch &gt; =&#39;A&#39; &amp;&amp; ch &lt; =&#39;Z&#39;) // Determines if the character is an alphabet and in <br /> { // upper case<br /> ucode=(int)ch;<br /> ucode=ucode+32;<br /> s1[i]=(char)ucode;<br /> }<br /> else // else retains the same case into the string object of <br /> { // the class<br /> s1[i]=ch;<br /> }<br /> return s1; // Method returns converted string<br /> }<br />}<br /></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2006/04/string-extractors-and-manipulators-in-c-part-iv/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# String Class</title>
		<link>http://www.csharphelp.com/2006/03/c-string-class/</link>
		<comments>http://www.csharphelp.com/2006/03/c-string-class/#comments</comments>
		<pubDate>Wed, 22 Mar 2006 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Strings]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=125</guid>
		<description><![CDATA[This program explores the &#39;String&#39; class, with this you will be able to create the string using the constructors and explore all the methods in this class. Download stringclass.cs]]></description>
			<content:encoded><![CDATA[<p><span style="font-size:xx-small;"><b><br /></b></span><span class="smallblack"><a href="http://www.csharphelp.com/bio/thang.html"></a></span></p>
<p><span class="smallblack">This program explores the &#39;String&#39; class, with this you will be able to create the string using the constructors and explore all the methods in this class.</span></p>
<p><span class="smallblack">Download <a href="http://www.csharphelp.com/archives/files/archive126/stringclass.cs">stringclass.cs</a></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2006/03/c-string-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

