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,228
  • 4
  • 33
  • 46

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
  • 52,773
  • 10
  • 120
  • 121
5
resultString = Regex.Replace("MyUnsolvedProblem", "([a-z])([A-Z])", "$1 $2");
ipr101
  • 23,772
  • 7
  • 57
  • 61
2

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
  • 59,352
  • 21
  • 103
  • 153
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
  • 44,682
  • 8
  • 70
  • 108