Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
c# Put spaces between words starting with capital letters
To place spaces between words starting with capital letters in C#, you can use LINQ to examine each character and insert spaces before uppercase letters. This technique is commonly used to format PascalCase strings into readable text.
Syntax
The basic syntax using LINQ to add spaces before capital letters −
string.Concat(str.Select(x => Char.IsUpper(x) ? " " + x : x.ToString())).TrimStart(' ');
Using LINQ with Select and IsUpper
The following example demonstrates how to add spaces before each uppercase letter in a PascalCase string −
using System;
using System.Linq;
class Demo {
static void Main() {
var str = "WelcomeToMyWebsite";
Console.WriteLine("Original String: " + str);
str = string.Concat(str.Select(x => Char.IsUpper(x) ? " " + x : x.ToString())).TrimStart(' ');
Console.WriteLine("New String: " + str);
}
}
The output of the above code is −
Original String: WelcomeToMyWebsite New String: Welcome To My Website
Using Regular Expressions
An alternative approach uses regular expressions to insert spaces before uppercase letters −
using System;
using System.Text.RegularExpressions;
class Demo {
static void Main() {
string str = "HelloWorldFromCSharp";
Console.WriteLine("Original String: " + str);
string result = Regex.Replace(str, "([A-Z])", " $1").Trim();
Console.WriteLine("New String: " + result);
}
}
The output of the above code is −
Original String: HelloWorldFromCSharp New String: Hello World From C Sharp
Using StringBuilder for Better Performance
For larger strings, StringBuilder provides better performance −
using System;
using System.Text;
class Demo {
static void Main() {
string str = "MyVeryLongPascalCaseString";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.Length; i++) {
if (i > 0 && Char.IsUpper(str[i])) {
sb.Append(' ');
}
sb.Append(str[i]);
}
Console.WriteLine("Original String: " + str);
Console.WriteLine("New String: " + sb.ToString());
}
}
The output of the above code is −
Original String: MyVeryLongPascalCaseString New String: My Very Long Pascal Case String
Comparison of Methods
| Method | Pros | Cons |
|---|---|---|
| LINQ with Select | Concise, functional approach | Less efficient for large strings |
| Regular Expressions | Powerful pattern matching | Requires System.Text.RegularExpressions |
| StringBuilder Loop | Best performance for large strings | More verbose code |
Conclusion
Adding spaces between words starting with capital letters in C# can be accomplished using LINQ, regular expressions, or StringBuilder. The LINQ approach is concise for small strings, while StringBuilder offers better performance for larger text processing tasks.
