We help IT Professionals succeed at work.

How to capitalise first letter of every word

katym
katym asked
on
462 Views
Last Modified: 2012-08-14
Hi
I have an address text box which allows our users to enter their address which is then put in the DB.  i wish to change the text to be TitleCase (where each word begins with a capital letter then lower case).
I can get it to work for words that are spilt by a space OR words that are spilt by a new line but i cant get it to work for both!

for example....

entered text:
flat 1 downing street
london
england

I want it to become.....

Flat 1 Downing Street
London
England

but get only get

EITHER...
(new line spilt)
Flat 1 downing street
London
England

OR
(space spilt)
flat 1 Downing Street
london
england


could someone please help?.....any would be much appreciated!....I am very new to C#  :-)
new-line-code.txt
space-code.txt
Comment
Watch Question

CERTIFIED EXPERT

Commented:
char[] delimiterChars = { '\n', ' ' };

Commented:
Hi katym,
You can used a regular expression replace to do this, just replace the strInputText with the input text and the strCapitalizedText will be the input.

Enjoy!
P.
string strCapitalizedText = System.Text.RegularExpressions.Regex.Replace(strInputText, @"(\b\S)(\S*\b)", delegate(Match m) { return m.Result("$1").ToUpper() + m.Result("$2").ToLower(); });

Open in new window

Commented:
oops, I meant strCapitalizedText will be the output.

I've attached it again, might be easier to read.  :)
string strCapitalizedText = System.Text.RegularExpressions.Regex.Replace(strInputText, @"(\b\S)(\S*\b)", 
                delegate(Match m) 
                { 
                    return m.Result("$1").ToUpper() + m.Result("$2").ToLower(); 
                });

Open in new window

Commented:
the easiest way in C# would be...

string title = "some string:;
CultureInfo cultureInfo   = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
Console.WriteLine(textInfo.ToTitleCase(title));

Commented:
Hi DannyDH,
I wish I'd known about the TextInfo class before this.  Anyhow, nice work, I learned something new today.
P.

Author

Commented:
Thanks p davis....i already thought of that but got stuck with concatenating the text back together in the format i need,
i.e. result += s.Substring(0, 1).ToUpper() + s.Substring(1).ToLower() + '\n';

Author

Commented:
thank you Pui_Yun.
Please could you explain how your code works?

Author

Commented:
hiya

i tried the above suggestions but couldnt get them to work (i have very basic skill in c#!) so i have tried a different approach.....
i first replace any new lines with a comma and then split this to capitalise the first letter, then replace the commas back to ta new line.
it works to a pooint but returns the address as it was first entered and then the 'new' address with the correct capitals and new lines etc
e.g.
flat 1 downing street
london
englandFlat 1 Downing Street
London
England

the code is below...again all help is much appreciated :-)



public static string FormatString(string text, bool toUpper, bool toLower, bool toInit)
    {
        if (toUpper)
            return text.ToUpper();

        if (toLower)
            return text.ToLower();

        if (toInit)
        {      
           
            string replaced = "";
           
            if (text.Contains("\r\n"))
            replaced = text.Replace("\r\n", ",");
            replaced = text.Replace("\r", ",");
            replaced = text.Replace("\n", ",");

            string[] t = replaced.Split(new Char[] { ' ', ',' });

            foreach (string s in t)
            {
                if (s.Length == 1)
                    replaced += s.ToUpper() + " ";
                else
                    if (s.Length > 1)
                        replaced += s.Substring(0, 1).ToUpper() + s.Substring(1).ToLower() + " ";
            }

            if (replaced.Contains(","))
                replaced = replaced.Replace(",", "\n");
            return replaced;
        }
        return text;
    }

Commented:
Hi Katym,
Were you able to get my code to work?  Basically, how my code works is that I use regular expression (string pattern recognition) to match on the first letter and also the rest of the word and do a replacement of those string using an inline function - capitalizing the first letter and lowercasing the rest.  

Here's a good small 30 minutes tutorial about regular expressions:
http://www.codeproject.com/KB/dotnet/regextutorial.aspx

You may have noticed that I have use a delegate, which basically an inline function, i.e. passing an entire function to the Replace method of the Regex object.  The output of this is what the replace with output each time it finds a match based on the regex pattern that I gave it.

Hope this helps!
P.

Author

Commented:
thanks Pui Yun

i try this...
public static string FormatString(string text)
  {
 
            string strCapitalizedText = System.Text.RegularExpressions.Regex.Replace(text, @"(\b\S)(\S*\b)",
                 delegate(Match m)
                 {
                     return m.Result("$1").ToUpper() + m.Result("$2").ToLower();
                 });
  }
       

but i get this error.....CS0161: 'WebSite.OnlineServices.FormatString(string)': not all code paths return a value
what am i doing wrong...this is driving me mad!
CERTIFIED EXPERT

Commented:
public static string FormatString(string text)
  {
 
            string strCapitalizedText = System.Text.RegularExpressions.Regex.Replace(text, @"(\b\S)(\S*\b)",
                 delegate(Match m)
                 {
                     return m.Result("$1").ToUpper() + m.Result("$2").ToLower();
                 });

return null;
  }
CERTIFIED EXPERT

Commented:
or

return String.Empty;

Commented:
Hi katym,

You're function doesn't return anything, which is the problem, the return in the delegate has nothing to do with your function.  Try this:

Hope this helps!
P.
public static string FormatString(string text)
  {
 
            string strCapitalizedText = System.Text.RegularExpressions.Regex.Replace(text, @"(\b\S)(\S*\b)",
                 delegate(Match m)
                 {
                     return m.Result("$1").ToUpper() + m.Result("$2").ToLower();
                 }); 
return strCapitalizedText;
  }

Open in new window

Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
it worked!!  thank you so much Pui Yun and p davis, it does exactly what i wanted.
:-)
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.