<?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>Now coding&#8230;</title>
	<atom:link href="http://nowcoding.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://nowcoding.net</link>
	<description>Pablo Fernandez Duran</description>
	<lastBuildDate>Sun, 02 Mar 2014 18:30:42 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.1.10</generator>
	<item>
		<title>[F#] Common Intersection of a sequence of sequences</title>
		<link>http://nowcoding.net/fsharp-common-intersection-of-a-sequence-of-sequences/</link>
					<comments>http://nowcoding.net/fsharp-common-intersection-of-a-sequence-of-sequences/#respond</comments>
		
		<dc:creator><![CDATA[Pablo]]></dc:creator>
		<pubDate>Thu, 20 Feb 2014 18:21:19 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[intersection]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[reduce]]></category>
		<category><![CDATA[sequences]]></category>
		<category><![CDATA[set]]></category>
		<guid isPermaLink="false">http://nowcoding.net/?p=138</guid>

					<description><![CDATA[The idea is to find the common intersection of a sequence of sequences — or lists or arrays (in red in the image below). Let&#8217;s say we have a bunch of CSV files and we want to find all the common columns between these files. We are goint to use the following data for testing: [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>The idea is to find the common intersection of a sequence of sequences — or lists or arrays (in red in the image below).</p>
<div id="attachment_140" style="width: 592px" class="wp-caption aligncenter"><a href="http://nowcoding.net/wp-content/uploads/2014/02/intersection1.png"><img aria-describedby="caption-attachment-140" decoding="async" class="size-full wp-image-140" alt="Intersection of 3 sets" src="http://nowcoding.net/wp-content/uploads/2014/02/intersection1.png" width="582" height="471" srcset="http://nowcoding.net/wp-content/uploads/2014/02/intersection1.png 582w, http://nowcoding.net/wp-content/uploads/2014/02/intersection1-300x242.png 300w" sizes="(max-width: 582px) 100vw, 582px" /></a><p id="caption-attachment-140" class="wp-caption-text">Intersection of 3 sets</p></div>
<p>Let&#8217;s say we have a bunch of CSV files and we want to find all the common columns between these files.<br />
<span id="more-138"></span><br />
We are goint to use the following data for testing:</p>
<pre class="brush: fsharp; title: ; notranslate">
let headersByFile = seq{
    yield &#x5B; &quot;id&quot;; &quot;name&quot;; &quot;date&quot;; &quot;color&quot; ]
    yield &#x5B; &quot;id&quot;; &quot;age&quot;; &quot;date&quot; ]
    yield &#x5B; &quot;id&quot;; &quot;sex&quot;; &quot;date&quot;; &quot;animal&quot; ]
}
// val headersByFile : seq&lt;string list&gt;
</pre>
<p>And we want to have as result:</p>
<pre class="brush: fsharp; title: ; notranslate">
&#x5B; &quot;id&quot;; &quot;date&quot; ]
</pre>
<p>As the Intersection operation is associative:</p>
<pre class="brush: plain; title: ; notranslate">
(A ∩ B) ∩ C = A ∩ (B ∩ C)
</pre>
<p>We can compute the intersection of the first list and the second list and then use the result to compute the intersection with the third list and so on.</p>
<p>That sounds like a familiar high order function: <a title="Seq.reduce&lt;'T&gt; Function (F#)" href="http://msdn.microsoft.com/en-us/library/ee353740.aspx" target="_blank">Seq.reduce</a>.</p>
<p>In F# we don&#8217;t have a built-in function to compute the intersection of two lists or sequences — as we do in C# with <a title="Enumerable.Intersect&lt;TSource&gt; Method (IEnumerable&lt;tsource&gt;, IEnumerable&lt;/tsource&gt;&lt;tsource&gt;)" href="http://msdn.microsoft.com/en-us/library/bb460136(v=vs.110).aspx" target="_blank">Enumerable.Intersect</a> — but we do have an <a title="Set.intersect&lt;'T&gt; Function (F#)" href="http://msdn.microsoft.com/en-us/library/ee353629.aspx" target="_blank">intersection </a>function in the <a title="Collections.Set Module (F#)" href="http://msdn.microsoft.com/en-us/library/ee340244.aspx" target="_blank">Set module</a> to work with sets, so we will use it.</p>
<p>First we need to transform our sequence of lists in a sequence of sets (working directly with our data):</p>
<pre class="brush: fsharp; title: ; notranslate">

let headersByFileSet = Seq.map Set.ofList headersByFile
// val headersByFileSet : seq&lt;Set&lt;string&gt;&gt;

</pre>
<p>We have now a sequence of sets in which we can apply a &#8216;reduction&#8217; using the <a title="Set.intersect&lt;'T&gt; Function (F#)" href="http://msdn.microsoft.com/en-us/library/ee353629.aspx" target="_blank">Set.intersect</a> function.</p>
<pre class="brush: fsharp; title: ; notranslate">

let commonHeaders = Seq.reduce Set.intersect headersByFileSet 
// val commonHeaders : Set&lt;string&gt; = set &#x5B;&quot;date&quot;; &quot;id&quot;]

</pre>
<p>And that is all!</p>
<p>A way to gather all this together is using the &#8216;<strong>pipeline</strong>&#8216; operator:</p>
<pre class="brush: fsharp; title: ; notranslate">
let commonHeaders = 
      headersByFile
      |&gt; Seq.map Set.ofList
      |&gt; Seq.reduce Set.intersect
// val commonHeaders : Set&lt;string&gt; = set &#x5B;&quot;date&quot;; &quot;id&quot;]
</pre>
<p>Or making even a generic function using &#8216;<strong>function composition</strong>&#8216; and &#8216;<strong>function partial application</strong>&#8216;:</p>
<pre class="brush: fsharp; title: ; notranslate">
let commonIntersection = Seq.map Set.ofList &gt;&gt; Seq.reduce Set.intersect
// val commonIntersection : (seq&lt;string list&gt; -&gt; Set&lt;string&gt;)

let commonHeaders = commonIntersection  headersByFileSet 
// val commonHeaders : Set&lt;string&gt; = set &#x5B;&quot;date&quot;; &quot;id&quot;]
</pre>
<p><strong>[Update]</strong><br />
There is built-in function in the Set module to calculate directly the common intersection of a sequence of sets: <a href="http://msdn.microsoft.com/en-us/library/ee353431.aspx" title="Set.intersectMany&gt;'T&lt; Function (F#)" target="_blank">Set.intersectMany</a>, so we only need to transform our sequence of lists to a sequence of sets.</p>
<pre class="brush: fsharp; title: ; notranslate">
let commonHeaders = 
      headersByFile
      |&gt; Seq.map Set.ofList
      |&gt; Set.intersectMany
// val commonHeaders : Set&lt;string&gt; = set &#x5B;&quot;date&quot;; &quot;id&quot;]
</pre>
]]></content:encoded>
					
					<wfw:commentRss>http://nowcoding.net/fsharp-common-intersection-of-a-sequence-of-sequences/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>[SQL Server] Display hierarchical data from a tree</title>
		<link>http://nowcoding.net/sql-server-display-hierarchical-data-from-a-tree/</link>
					<comments>http://nowcoding.net/sql-server-display-hierarchical-data-from-a-tree/#comments</comments>
		
		<dc:creator><![CDATA[Pablo]]></dc:creator>
		<pubDate>Fri, 13 Dec 2013 00:35:15 +0000</pubDate>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Common table expression]]></category>
		<category><![CDATA[Hierarchical data]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[With keyword]]></category>
		<guid isPermaLink="false">http://nowcoding.net/?p=123</guid>

					<description><![CDATA[It is common to have a hierarchical or tree structure table in a SQL model data. We would like to display the data as follow: But when it comes to display the raw data it is hard to identify the hierarchical form. Let&#8217;s build a very simple data model for the sake of example. Create [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>It is common to have a hierarchical or tree structure table in a SQL model data.</p>
<p>We would like to display the data as follow:</p>
<div id="attachment_126" style="width: 324px" class="wp-caption aligncenter"><a href="http://nowcoding.net/wp-content/uploads/2013/12/hierarchical.png"><img aria-describedby="caption-attachment-126" decoding="async" loading="lazy" src="http://nowcoding.net/wp-content/uploads/2013/12/hierarchical.png" alt="Hierarchical display data" width="314" height="353" class="size-full wp-image-126" srcset="http://nowcoding.net/wp-content/uploads/2013/12/hierarchical.png 314w, http://nowcoding.net/wp-content/uploads/2013/12/hierarchical-266x300.png 266w" sizes="(max-width: 314px) 100vw, 314px" /></a><p id="caption-attachment-126" class="wp-caption-text">Hierarchical display data</p></div>
<p>But when it comes to display the raw data it is hard to identify the hierarchical form.</p>
<p><span id="more-123"></span></p>
<div id="attachment_124" style="width: 291px" class="wp-caption aligncenter"><a href="http://nowcoding.net/wp-content/uploads/2013/12/not_hierarchical.png"><img aria-describedby="caption-attachment-124" decoding="async" loading="lazy" src="http://nowcoding.net/wp-content/uploads/2013/12/not_hierarchical.png" alt="Not hierarchical display" width="281" height="354" class="size-full wp-image-124" srcset="http://nowcoding.net/wp-content/uploads/2013/12/not_hierarchical.png 281w, http://nowcoding.net/wp-content/uploads/2013/12/not_hierarchical-238x300.png 238w" sizes="(max-width: 281px) 100vw, 281px" /></a><p id="caption-attachment-124" class="wp-caption-text">Not hierarchical display</p></div>
<p>Let&#8217;s build a very simple data model for the sake of example.</p>
<pre class="brush: sql; title: ; notranslate">
Create table Tree(
	nodeId int not null primary key,
	parentNodeId int null foreign key references Tree(nodeId),
	name nvarchar(max)
)
</pre>
<p>And insert some data.</p>
<pre class="brush: sql; title: ; notranslate">
insert into Tree values
(1, null, 'Root A'),
	(2, 1, 'Child A1'),
		(3, 2, 'Child A11'),
		(4, 2, 'Child A12'),
	(5, 1, 'Child A2'),
		(6, 5, 'Child A21'),
			(7, 6, 'Child A211'),
			(8, 6, 'Child A212'),
		(9, 5, 'Child A22'),
(10, null, 'Root B'),
(11, null, 'Root C'),
	(12, 11, 'Child C1'),
		(13, 12, 'Child C11'),
		(14, 12, 'Child C12'),
	(15, 11, 'Child C2')
</pre>
<p>Let&#8217;s use a <a href="http://msdn.microsoft.com/en-us/library/ms175972.aspx" title="WITH common_table_expression (Transact-SQL)" target="_blank">Common Table Expression (CTE)</a>:</p>
<pre class="brush: sql; title: ; notranslate">
;with orderedTree (name, nodeId, depth, location)
as
(
	select 
		name,
		nodeId,  
		0 as depth,
		CAST(nodeId AS nvarchar(max)) AS location
	from tree 
	where parentNodeId is null

	union all

	select 
		cast(concat(space(parent.depth * 5), '|__', child.name) as nvarchar(max)), 
		child.nodeId, 
		parent.depth + 1,
		cast(concat(parent.location, '.' ,child.nodeId) AS nvarchar(max)) AS location
	from tree child
	inner join orderedTree parent
		on child.parentNodeId = parent.nodeId

)

select * from orderedTree
order by location
</pre>
<p>Now we can easily see the hierarchical structure of our data.</p>
]]></content:encoded>
					
					<wfw:commentRss>http://nowcoding.net/sql-server-display-hierarchical-data-from-a-tree/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Windows Forms, how to avoid a Dialog Box to close</title>
		<link>http://nowcoding.net/windows-forms-how-to-avoid-dialog-box-to-close/</link>
					<comments>http://nowcoding.net/windows-forms-how-to-avoid-dialog-box-to-close/#respond</comments>
		
		<dc:creator><![CDATA[Pablo]]></dc:creator>
		<pubDate>Sat, 09 Nov 2013 02:38:27 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WinForms]]></category>
		<category><![CDATA[Dialog Box]]></category>
		<category><![CDATA[DialogResult]]></category>
		<category><![CDATA[Modal From]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<guid isPermaLink="false">http://nowcoding.net/?p=94</guid>

					<description><![CDATA[When displaying a Form as a Dialog/Modal Box sometimes you may need to avoid the Dialog form to close. Let&#8217;s say we have a main form that displays another form as a Modal dialog to finally display some information from that form. Here is the code for the &#8220;Choose your favorite pet&#8221; Dialog form: public [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>When displaying a Form as a Dialog/Modal Box sometimes you may need to avoid the Dialog form to close.</p>
<p>Let&#8217;s say we have a main form that displays another form as a Modal dialog to finally display some information from that form.</p>
<p><div id="attachment_95" style="width: 932px" class="wp-caption aligncenter"><a href="http://nowcoding.net/wp-content/uploads/2013/11/forms.png"><img aria-describedby="caption-attachment-95" decoding="async" loading="lazy" src="http://nowcoding.net/wp-content/uploads/2013/11/forms.png" alt="Choose favorite pet form" width="922" height="428" class="size-full wp-image-95" srcset="http://nowcoding.net/wp-content/uploads/2013/11/forms.png 922w, http://nowcoding.net/wp-content/uploads/2013/11/forms-300x139.png 300w" sizes="(max-width: 922px) 100vw, 922px" /></a><p id="caption-attachment-95" class="wp-caption-text">Choose favorite pet form</p></div><br />
<span id="more-94"></span><br />
Here is the code for the &#8220;Choose your favorite pet&#8221; Dialog form:</p>
<pre class="brush: csharp; title: ; notranslate">
public partial class ChoosePetDialogForm : Form
{
    public string ChosenPet { get; private set; }

    public ChoosePetDialogForm()
    {
        InitializeComponent();
        ChosenPet = &quot;Nothing&quot;;
    }

    private void choosePetButton_Click(object sender, EventArgs e)
    {
        var petRadioChecked = this.petListGroup
                                    .Controls
                                    .OfType&lt;RadioButton&gt;()
                                    .FirstOrDefault(r =&gt; r.Checked);
        if (petRadioChecked != null)
        {
            ChosenPet = petRadioChecked.Text;
        }
    }
}
</pre>
<p>The <code>choosePetButton</code> is associated to a <code>DialogResult</code> of value <code>DialogResult.OK</code>:</p>
<div id="attachment_98" style="width: 961px" class="wp-caption aligncenter"><a href="http://nowcoding.net/wp-content/uploads/2013/11/diag.png"><img aria-describedby="caption-attachment-98" decoding="async" loading="lazy" src="http://nowcoding.net/wp-content/uploads/2013/11/diag.png" alt="Button Dialog Result" width="951" height="523" class="size-full wp-image-98" srcset="http://nowcoding.net/wp-content/uploads/2013/11/diag.png 951w, http://nowcoding.net/wp-content/uploads/2013/11/diag-300x164.png 300w" sizes="(max-width: 951px) 100vw, 951px" /></a><p id="caption-attachment-98" class="wp-caption-text">Button Dialog Result</p></div>
<p>That makes the <code>ChoosePetDialogForm</code> &#8220;return&#8221; the value <code>DialogResult.OK</code> when called as a Dialog Box when the <code>choosePetButton</code> is clicked.</p>
<p>And the code for the caller form:</p>
<pre class="brush: csharp; title: ; notranslate">
public partial class PetTestForm : Form
{
    public PetTestForm()
    {
        InitializeComponent();
    }

    private void takeTestButton_Click(object sender, EventArgs e)
    {
        ChoosePetDialogForm dialog = new ChoosePetDialogForm();
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            MessageBox.Show(dialog.ChosenPet, &quot;Pet Chosen:&quot;);
        }
    }
}
</pre>
<p>Let&#8217;s say now that I want to make some validation before the Modal Dialog form closes, for example allow only &#8220;platypus&#8221; as favorite pet. How can I make the modal dialog to continue running after clicking a button?</p>
<pre class="brush: csharp; title: ; notranslate">
if (!radioButtonPlatypus.Checked)
{
    // avoid the modal dialog to close
}
</pre>
<p>Well, as explained on the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.dialogresult(v=vs.110).aspx" title="DialogResult Enumeration" target="_blank">DialogResult Enumeration documentation</a>, we simply need to set the <code>DialogResult</code> property value of the Modal form to <code>DialogResult.None</code>.</p>
<pre class="brush: csharp; title: ; notranslate">
if (!radioButtonPlatypus.Checked)
{
    // avoid the modal dialog to close
    this.DialogResult = DialogResult.None;
    MessageBox.Show(&quot;Wrong pet! Try again.&quot;);
}
</pre>
<p>This way the Modal form will not close.</p>
]]></content:encoded>
					
					<wfw:commentRss>http://nowcoding.net/windows-forms-how-to-avoid-dialog-box-to-close/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Capitalize the first letter of names or Title Case</title>
		<link>http://nowcoding.net/capitalize-the-first-letter-of-names-or-title-case/</link>
					<comments>http://nowcoding.net/capitalize-the-first-letter-of-names-or-title-case/#respond</comments>
		
		<dc:creator><![CDATA[Pablo]]></dc:creator>
		<pubDate>Tue, 22 Oct 2013 22:48:01 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Regex]]></category>
		<category><![CDATA[bug]]></category>
		<category><![CDATA[legacy code]]></category>
		<category><![CDATA[regex replace]]></category>
		<category><![CDATA[Regular Expressions]]></category>
		<category><![CDATA[string manipulation]]></category>
		<category><![CDATA[Title Case]]></category>
		<guid isPermaLink="false">http://blog.polkduran.net/?p=64</guid>

					<description><![CDATA[The problem I was working on an application when suddenly I stepped into a method that intrigued me. public static string NameFormatter(string name) { if (!String.IsNullOrEmpty(name)) { int index = 1; char&#x5B;] separator = new&#x5B;] { ' ', '-', '_', '.', '\'' }; name = name.Substring(0, 1).ToUpper() + name.Substring(1); while ((index = name.IndexOfAny(separator, index)) &#38;gt; [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>The problem</h1>
<p>I was working on an application when suddenly I stepped into a method that intrigued me.</p>
<pre class="brush: csharp; title: ; notranslate">
public static string NameFormatter(string name)
{
    if (!String.IsNullOrEmpty(name))
    {
        int index = 1;
        char&#x5B;] separator = new&#x5B;] { ' ', '-', '_', '.', '\'' };
        name = name.Substring(0, 1).ToUpper() + name.Substring(1);
        while ((index = name.IndexOfAny(separator, index)) &amp;gt; 0)
        {
            index++;
            if (name.Length &amp;gt; index + 1)
            {
                name = name.Replace(
                                name.Substring(index, 1),
                                name.Substring(index, 1).ToUpper());
            }
        }
    }
    return name;
}
</pre>
<p><span id="more-64"></span><br />
This code has no comments and it has been in production since years, at least the method&#8217;s name gives a hint of its intention, this method is meant to format a <code><strong>string</strong></code> (like a name) replacing the first character after a given separator character (<code><strong>' ', '-', '_', '.', '\''</strong></code>) by its upper case form.</p>
<p>Let&#8217;s a make a test:</p>
<pre class="brush: csharp; title: ; notranslate">
string&#x5B;] names = {
                    &amp;quot;john f. smith&amp;quot;,
                    &amp;quot;sandra tayllor-murray&amp;quot;,
                    &amp;quot;miguel d'angelo&amp;quot;,
                    &amp;quot;pablo fernandez duran&amp;quot;
                    };

foreach (string name in names)
{
    Console.WriteLine(NameFormatter(name));
}

// output:
//     John F. Smith
//     Sandra Tayllor-Murray
//     Miguel D'Angelo
//     Pablo FernanDez Duran

</pre>
<p>It seems to work. Wait! I don&#8217;t really like how this application displays my last name (<code><strong>FernanDez</strong></code>). Leaving aside some algorithmic issues, let&#8217;s find the source of the problem. The incriminated line of code is:</p>
<pre class="brush: csharp; title: ; notranslate">
name = name.Replace(
                name.Substring(index, 1),
                name.Substring(index, 1).ToUpper());
</pre>
<p>Let&#8217;s say <code><strong>name.Substring(index, 1) = "d"</strong></code>.<br />
We have: <code><strong>name = name.Replace("d", "d".ToUpper())</strong></code>. Not only the character <strong>&#8220;d&#8221;</strong> at the index position is replaced but all the occurrences of <strong>&#8220;d&#8221;</strong> in the string are replaced.</p>
<h1>Fixing the code</h1>
<p>Let&#8217;s fix that:</p>
<pre class="brush: csharp; title: ; notranslate">
name =  name.Substring(0, index)
        + name.Substring(index, 1).ToUpper()
        + name.Substring(index + 1);

// name = name.Replace(
//                 name.Substring(index, 1),
//                 name.Substring(index, 1).ToUpper());
</pre>
<p>Now the output is:</p>
<pre class="brush: csharp; title: ; notranslate">
// John F. Smith
// Sandra Tayllor-Murray
// Miguel D'Angelo
// Pablo Fernandez Duran
</pre>
<h1>Using the TextInfo.ToTitleCase method</h1>
<p>That&#8217;s better, but I&#8217;m not still happy about this code, a lot of <em>noise</em>, difficult to maintain, the main intention of the algorithm it&#8217;s hidden in its implementation and so on. Before trying to rewrite the method let&#8217;s see if there is something in the .NET framework that can be useful. We have the <a title="TextInfo.ToTitleCase Method" href="http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase(v=vs.100).aspx" target="_blank"><code><strong>TextInfo.ToTitleCase</strong></code></a> Method.</p>
<p>Let&#8217;s make a test:</p>
<pre class="brush: csharp; title: ; notranslate">
string&#x5B;] names = {
                    &amp;quot;john f. smith&amp;quot;,
                    &amp;quot;sandra tayllor-murray&amp;quot;,
                    &amp;quot;miguel d'angelo&amp;quot;,
                    &amp;quot;pablo fernandez duran&amp;quot;
                    };
TextInfo textInfo = new CultureInfo(&amp;quot;en-US&amp;quot;, false).TextInfo;
foreach (string name in names)
{
    Console.WriteLine(textInfo.ToTitleCase(name));
}

// output:
//    John F. Smith
//    Sandra Tayllor-Murray
//    Miguel D'angelo
//    Pablo Fernandez Duran
</pre>
<p>Almost there! now Miguel wouldn&#8217;t like how the application displays his name (I don&#8217;t really know any Miguel D&#8217;Angelo).</p>
<p>I tried with other <em>cultures</em> but I didn&#8217;t see any difference (and I would like to know if there is a difference between different cultures).</p>
<h1>Using Regular Expressions</h1>
<p>What to do now? Let&#8217;s use a <strong>regex</strong>.</p>
<pre class="brush: csharp; title: ; notranslate">
public static string NameFormatter(string name)
{
    if (!String.IsNullOrEmpty(name))
    {
        return Regex.Replace(
                         name,
                         @&amp;quot;\b&#x5B;a-zA-Z]&amp;quot;,
                         m =&amp;gt; m.Value.ToUpper());
    }
    return name;
}
// output:
//    John F. Smith
//    Sandra Tayllor-Murray
//    Miguel D'Angelo
//    Pablo Fernandez Duran
</pre>
<p>Great! <code><strong>\b[a-zA-Z]</strong></code> will find all characters between <strong>a to z</strong> and <strong>A to Z</strong> just after a <strong>word boundary</strong> (<code><strong>\b</strong></code>). More information about <code><strong>Regex.Replace</strong></code> <a title="Regex.Replace Method (String, String, MatchEvaluator)" href="http://msdn.microsoft.com/en-us/library/vstudio/ht1sxswy(v=vs.110).aspx" target="_blank">here</a>.</p>
<p>One case is not covered with this <strong>regex</strong>: characters following a <strong>&#8216;_&#8217;</strong> (underscore). That is because the word boundary <code><strong>\b</strong></code> by definition considers as word characters the <em>&#8220;character class&#8221;</em> <code><strong>\w</strong></code>, and <code><strong>\w</strong></code> is the short hand for <code><strong>[A-Za-z0-9_]</strong> </code>.</p>
<p>Let&#8217;s tune our <strong>regex </strong> to the handle the <strong>_</strong> character as a separator: <code><strong>(?&lt;=\b|_)[a-zA-Z]</strong></code>.</p>
<h1>Bonus</h1>
<p>To handle names like mcfry or macdonald&#8217;s we can use:<br />
<code><strong>(?&lt;=\b(?:mc|mac)?|_)[a-zA-Z](?&lt;!'s\b)</strong></code></p>
<ul>
<li>john f. smith</li>
<li>sandra tayllor-murray</li>
<li>miguel d&#8217;angelo</li>
<li>pablo fernandez duran</li>
<li>mcfry</li>
<li>macdonald&#8217;s</li>
</ul>
<p>Will give:</p>
<ul>
<li>John F. Smith</li>
<li>Sandra Tayllor-Murray</li>
<li>Miguel D&#8217;Angelo</li>
<li>Pablo Fernandez Duran</li>
<li>McFry</li>
<li>MacDonald&#8217;s</li>
</ul>
<p>The final code is:</p>
<pre class="brush: csharp; title: ; notranslate">
public static string NameFormatter(string name)
{
    if (!String.IsNullOrEmpty(name))
    {
        return Regex.Replace(
                         name,
                         @&amp;quot;(?&amp;lt;=\b(?:mc|mac)?|_)&#x5B;a-zA-Z](?&amp;lt;!'s\b)&amp;quot;,
                         m =&amp;gt; m.Value.ToUpper());
    }
    return name;
}
</pre>
<h1>Finally</h1>
<p>We need to do some extra work on the <strong>regex </strong>if we want to match an extended range of characters like diacritics (<strong>accents</strong>), take a look at the <a title="Character Classes in Regular Expressions" href="http://msdn.microsoft.com/en-us/library/20bw873z.aspx" target="_blank">Character classes in regex reference</a> on the smdn or <a title="Unicode Regular Expressions" href="http://www.regular-expressions.info/unicode.html" target="_blank">here</a>. You can use this set to match also accents:<br />
<code><strong>[a-zA-ZÀ-ÿ]</strong></code>.</p>
<h1>Warning</h1>
<blockquote><p>Formatting names is a delicate question, it may depend on cultures and languages. The name is the identity of a person and people may no like that an application tells them how to write their name. So maybe the best way to format a name is to leave it as typed by the user. </p></blockquote>
]]></content:encoded>
					
					<wfw:commentRss>http://nowcoding.net/capitalize-the-first-letter-of-names-or-title-case/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
