6

Possible Duplicate:
An algorithm to "spacify" CamelCased strings

I have a string like this: MyUnsolvedProblem

I want to modify the string like this: My Unsolved Problem

How can I do that? I have tried using Regex with no luck!

Community
  • 1
  • 1
NaveenBhat
  • 3,248
  • 4
  • 35
  • 48

4 Answers4

12
var result = Regex.Replace("MyUnsolvedProblem", @"(\p{Lu})", " $1").TrimStart();

Without regex:

var s = "MyUnsolvedProblem";
var result = string.Concat(s.Select(c => char.IsUpper(c) ? " " + c.ToString() : c.ToString()))
    .TrimStart();
Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
5
resultString = Regex.Replace("MyUnsolvedProblem", "([a-z])([A-Z])", "$1 $2");
ipr101
  • 24,096
  • 8
  • 59
  • 61
3

LINQ based approach:

string data = "TestStringData";
var converted = data.Select(x => Char.IsUpper(x) ? String.Concat(" ", x) : x.ToString());
var singleString = converted.Aggregate((a, b) => a + b);
sll
  • 61,540
  • 22
  • 104
  • 156
1

I can offer a suggestion of how to do it in C# if that helps:

String PreString = "getAllItemsByID";

System.Text.StringBuilder SB = new System.Text.StringBuilder();

foreach (Char C in PreString)
{
    if (Char.IsUpper(C))
        SB.Append(' ');
    SB.Append(C);
}

Response.Write(SB.ToString());

I'm sure that there is a way to do it with regular expressions too, but this is one option.

James Johnson
  • 45,496
  • 8
  • 73
  • 110