1

I'm trying to capitalize words with c# applying this

Regex.Replace(source,"\b.",m=>m.Value.ToUpper())

It doesn't work.

I want to do this with c#:

"this is an example string".replace(/\b./g,function(a){ return a.toLocaleUpperCase()});

Output string: "This Is An Example String"

Tim S.
  • 55,448
  • 7
  • 96
  • 122
pedritin
  • 47
  • 2
  • 10
  • What output do you expect? – Tim S. May 13 '13 at 19:48
  • I don't agree that this question is exactly a duplicate. The linked to question has much more specific needs about which words should and should not be capitalized. If anything this question is more general and the other is too specific. – Robert Noack May 09 '14 at 04:05

4 Answers4

3

If you mean just the first letter of each word try this: ToTitleCase

http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx

string s = "this is an example string";
TextInfo ti = CultureInfo.CurrentCulture.TextInfo;

string uppercase = ti.ToTitleCase(s);
Robert Noack
  • 1,286
  • 14
  • 22
  • ToTitleCase() doesn't exist anymore in .NET Windows Store. You will need to rely on ToUpper() only. – Cœur Jun 21 '13 at 13:20
  • It's not in Metro, but it is in .NET 4.5, the question does not mention Metro and is tagged with .net-4.5 – Robert Noack Jun 24 '13 at 20:11
2

The issue is that you need to escape your search term, as it involves the '\' character. Use either @"\b." or "\\b." for your search term.

Eric Johnson
  • 191
  • 1
  • 3
1

Why don't you simply try this

string upperString = mystring.ToUpper();

If you want to first letter of each word in upper case then you can try this.

CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
string capitalString=textInfo.ToTitleCase(myString));
Sachin
  • 40,216
  • 7
  • 90
  • 102
0

You can also capitalize each word by aggregating.

"this is an example string"
.Split(' ')
.Aggregate("", (acc, word) => acc + " " + char.ToUpper(word[0]) + word.Substring(1))
Steven Wexler
  • 16,589
  • 8
  • 53
  • 80