user1926138
user1926138

Reputation: 1514

How to capitalise word in a string

I have a string like web_shop_settings and want it as Web Shop Settings. How to achieve it in C#.

Upvotes: 0

Views: 144

Answers (4)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186748

You can try using Linq:

  string source = @"web_shop_settings";

  string result = string.Concat(source.Select((c, i) => c == '_'
    ? ' '
    : i == 0 || Char.IsWhiteSpace(source[i - 1]) || source[i - 1] == '_' 
       ? Char.ToUpper(c) 
       : c));

Upvotes: 2

Petros Muradyan
Petros Muradyan

Reputation: 1

You can use this code snippet.

public static class StringExtensions
{
    public static string Capitalize(this string source, char separator)
    {
        return 
            string.Join(" ", source.Split(new char[] { separator }).Select(
                c =>
                string.Format("{0}{1}", c[0].ToString().ToUpper(), c.Length > 1 ? c.Substring(1) : "")));
    }
}
public class Program
{
    static void Main(string[] args)
    {
        var testString = "web_shop_settings";
        Console.WriteLine(testString.Capitalize('_'));
    }
}

Upvotes: 0

RVid
RVid

Reputation: 1287

You have the answer with regex so I thought I would add something done manually for reference:

        public string Transform(string input)
        {
            var stringBuilder = new StringBuilder();
            string separator = null;

            foreach (var word in input.Split('_').Where(w => w.Length > 0))
            {
                if (separator == null)
                    separator = " ";
                else
                    stringBuilder.Append(separator);

                var firstLetter = word.Substring(0, 1);
                stringBuilder.Append(firstLetter.ToUpper());
                stringBuilder.Append(word.Substring(1));
            }
            return stringBuilder.ToString();
        }

Upvotes: 1

Lucero
Lucero

Reputation: 60190

Regex.Replace(input, @"(?:_|^)(\p{L})", (match) => (match.Index > 0 ? " " : "")+match.Groups[1].Value.ToUpper())

Upvotes: 2

Related Questions