PDA

View Full Version : Upper case words



melissa820
12-07-2005, 03:52 PM
In PHP there is a function called ucwords where it capitalizes the first letter of each word in a string, and the rest of the word is set to lowercase.

Is there a similar string function in C#?

I want to change this: "hi there"
to this: "Hi There"

Nischumacher
12-07-2005, 04:20 PM
as far as i know... there is no predefined way to capitalize strings in C#...
you have to code for it...

melissa820
12-07-2005, 06:39 PM
In that case does anyone know of a place I could grab a function that does this? It must have been done before....

Brandoe85
12-07-2005, 07:27 PM
This could be a fun one to use a Regex on. Hopefully I'll get time to give it a shot later. But if your string is always separated with spaces, you can just split on the space, and put the peices back together:


private static string Capital(string strVal)
{
if(strVal == string.Empty)
{
throw new ArgumentNullException("Boo", "string not passed");
}

string[] parts = strVal.Split(" ".ToCharArray());
strVal = null;
for(int i = 0; i < parts.Length; i++)
{
strVal += parts[i].Substring(0, 1).ToUpper() + parts[i].Substring(1).ToLower() + " ";
}

return strVal;
}

// example
Capital("hello world");


Good luck;

melissa820
12-07-2005, 08:42 PM
Thanks, this is great :)