Link to home
Start Free TrialLog in
Avatar of Starr Duskk
Starr DuskkFlag for United States of America

asked on

Converting string to initial caps: my_field_name

I'm retrieving a fieldname from a table and want to convert it to initial caps and remove the underscore like so:

my_field_name
to
MyFieldName

How do I do that? I'm using vb.net but C# is fine if that is all you know.

thanks!
ASKER CERTIFIED SOLUTION
Avatar of PaulHews
PaulHews
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
or even
Private Function ConvertFieldName(Name As String) As String
    Return StrConv(Name.Replace("_", String.Empty), VbStrConv.ProperCase)
End Function

Open in new window

nepaluz,

Not quite as that returns "Myfieldname" not "MyFieldName"
Here is the code for you:-

private static string ToTitleCase(string text, char splitCharacter)
        {
            var txtInfo = new CultureInfo("en-US", false).TextInfo;
            var builder = new StringBuilder();

            text.Split(splitCharacter).ToList().ForEach(s => builder.Append(txtInfo.ToTitleCase(s)));
            return builder.ToString();
        }

Open in new window


Here is how to use this:-

string test = "my_field_name";
ToTitleCase(test,'_');

Open in new window

Add the following namespace:-
using System.Globalization;
Avatar of Starr Duskk

ASKER

Perfect!