Javed Akram
Javed Akram

Reputation: 15344

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

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

Upvotes: 13

Views: 30208

Answers (8)

Shoua Ul Qammar
Shoua Ul Qammar

Reputation: 233

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

Upvotes: 0

Leandro Bardelli
Leandro Bardelli

Reputation: 11578

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));

Upvotes: 0

mART
mART

Reputation: 31

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

string.Join("", str.Split(" ").Select(x => x[0]).ToArray())

Upvotes: 2

Manjunath Bilwar
Manjunath Bilwar

Reputation: 2353

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

Upvotes: 6

Tomas Jansson
Tomas Jansson

Reputation: 23462

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.

Upvotes: 1

Artem Tikhomirov
Artem Tikhomirov

Reputation: 21686

Regular expressions could be the answer:

  Regex.Matches(text, @"\b(\w{1})")
    .OfType<Match>()
    .Select(m => m.Groups[1].Value)
    .ToArray();

Upvotes: 4

Cheng Chen
Cheng Chen

Reputation: 43513

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.

Upvotes: 25

Kerri Brown
Kerri Brown

Reputation: 1187

string str = "This is my style"; 
str.Split(' ').ToList().ForEach(i => Console.Write(i[0] + " "));

Upvotes: 15

Related Questions