Rob P.
Rob P.

Reputation: 15091

Character Replacement In LINQ?

I was trying to put together a solution to: Insert spaces between words on a camel-cased token

Essentially, he wants to turn 'ThisIsATest' into 'This Is A Test'. I thought, 'Oh, that's easy, I can do it with LINQ' but I struggled with it.

Can someone help me?

Dim s As String = String.Join("", From myChar As Char In myStr _
                                  Select If(Char.IsUpper(myChar), (" " & myChar).ToString, myChar.ToString))

Is the path I started to go down, but I'm having trouble getting the results into something I can work with. I even added the .ToString to try and get back an array of Strings, but I'm still getting an error.

Unable to cast object of type 'WhereSelectEnumerableIterator`2[System.Char,System.String]' to type 'System.String[]'.

I believe that means I'm getting a collection of System.Char, System.String instead of just a System.String like I want.

What am I doing wrong?

Upvotes: 2

Views: 1718

Answers (3)

Leons
Leons

Reputation: 2674

You can use RegEx and split on the uppercase characters.

Dim myString as string = "ThisIsATest"
Dim outStr As String = Regex.Replace(myString,"[A-Z]"," $0")

The case-sensitive replace will locate every uppercase character and insert a space in front of the character.

Upvotes: 5

max
max

Reputation: 34447

C#:

var myStr = "TestString";
var outStr = string.Concat(myStr.Select(c => char.IsUpper(c) ? " " + c : c.ToString()));

auto-translated to VB.NET:

Dim myStr = "TestString"
Dim outStr = String.Concat(myStr.[Select](Function(c) If(Char.IsUpper(c), " " & Convert.ToString(c), c.ToString())))

Upvotes: 1

Bala R
Bala R

Reputation: 109027

You need to convert the second parameter to String[]. You can use .ToArray()

Dim outStr As String = String.Join("", (From myChar As Char In myStr _
                                               Select If(Char.IsUpper(myChar), (" " & myChar).ToString, myChar.ToString)).ToArray())

Upvotes: 2

Related Questions