shortest way to get first char from every word in a string
Asked Answered
B

8

13

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.Split(' ');
foreach(string s in output)
{
   Console.Write(s[0]+" ");
}

// Output
T i m s

I want to display same output with a shortest way...

Thanks

Bosworth answered 17/1, 2011 at 13:4 Comment(2)
Well, that is pretty much the shortest way.Chronister
I actually don't see anything wrong with this method. It's readable and does what it says on the box. Why do you want shorter? Just because something is shorter does not mean it is readable or obvious to what you are doing. What you have here doesn't even need commenting.Haim
G
15
string str = "This is my style"; 
str.Split(' ').ToList().ForEach(i => Console.Write(i[0] + " "));
Guesstimate answered 17/1, 2011 at 13:13 Comment(1)
Using Array.ForEach(str.Split(' '), s => Console.Write(s[0] + " ")); would be slightly shorter and faster. You might also want to use StringSplitOptions.RemoveEmptyEntries to handle the situation where the string starts with a space or contains consecutive spaces.Millardmillboard
M
25
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.

Makeweight answered 17/1, 2011 at 13:9 Comment(1)
Use .Split(" ", StringSplitOptions.RemoveEmptyEntries) instead to avoid errors on multiple spaces.Rachal
G
15
string str = "This is my style"; 
str.Split(' ').ToList().ForEach(i => Console.Write(i[0] + " "));
Guesstimate answered 17/1, 2011 at 13:13 Comment(1)
Using Array.ForEach(str.Split(' '), s => Console.Write(s[0] + " ")); would be slightly shorter and faster. You might also want to use StringSplitOptions.RemoveEmptyEntries to handle the situation where the string starts with a space or contains consecutive spaces.Millardmillboard
P
6

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
Phosphorate answered 16/9, 2019 at 21:41 Comment(1)
string SampleText = "Stack Overflow Com"; string ShortName = ""; SampleText .Split(' ').ToList().ForEach(i => ShortName += i[0].ToString());Infrequency
E
4

Regular expressions could be the answer:

  Regex.Matches(text, @"\b(\w{1})")
    .OfType<Match>()
    .Select(m => m.Groups[1].Value)
    .ToArray();
Eadwina answered 17/1, 2011 at 13:15 Comment(0)
O
2

For me this worked better then the others and still very flexible:

string.Join("", str.Split(" ").Select(x => x[0]).ToArray())
Orsa answered 1/4, 2021 at 12:27 Comment(2)
how this is better than the others if is the same answer but with a join?Bilberry
@Leandro: it's better for 'simple folk' like me who are searching for a method to get an abbreviation for a name (John Doe => JD). But you're correct, in the essence of the question, there is nothing new or better.Orsa
B
1

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.

Brayer answered 17/1, 2011 at 13:10 Comment(2)
You will have a problem if the string starts with ' '.Makeweight
Yep... I added a reservation note for that.Brayer
B
0

I work it with a list using LukeH consideration.

List<string> output = new List<string>();
Array.ForEach(str.Split(' ', StringSplitOptions.RemoveEmptyEntries), s => output.Add(s));
Bilberry answered 7/6, 2021 at 15:38 Comment(0)
Q
0

string.Join("", YourString.Split(' ').ToList().Select(s => s[0]));

Quito answered 29/5, 2024 at 6:50 Comment(2)
same answer as @mArtAconcagua
yes approx as mArt but no need to use .ToArray() whatever it'll be fast without .ToArray() @EfraimNewmanQuito

© 2022 - 2025 — McMap. All rights reserved.