I want a shortest way to get 1st char of every word in a string in C#.
what I have done is:
string str = \"This is my style\";
string [] output = str
Print first letter of each word in a string
string SampleText = "Stack Overflow Com";
string ShortName = "";
SystemName.Split(' ').ToList().ForEach(i => ShortName += i[0].ToString());
Output:
SOC
I think your solution is perfectly fine, but if you want better performance you can try:
string str = "This is my style";
Console.Write(str[0]);
for(int i = 1; i < str.Length; i++)
{
if(str[i-1] = " ")
Console.Write(" " + str[i]);
}
You might get a lower constant factor with this code but it still runs in O(n). Also, I assume that there will never be more than one space in a row and it won't start with space.
If you want to write less code you can try:
str result = str.Split(" ").Select(y => y[0]).ToList();
Or something.
Regular expressions could be the answer:
Regex.Matches(text, @"\b(\w{1})")
.OfType<Match>()
.Select(m => m.Groups[1].Value)
.ToArray();
string str = "This is my style";
str.Split(' ').ToList().ForEach(i => Console.Write(i[0] + " "));
var firstChars = str.Split(' ').Select(s => s[0]);
If the performance is critical:
var firstChars = str.Where((ch, index) => ch != ' '
&& (index == 0 || str[index - 1] == ' '));
The second solution is less readable, but loop the string once.