We help IT Professionals succeed at work.

Get first letter of each word in a phrase

karelog
karelog used Ask the Experts™
on
Hello Everybody!

I need to get the first letter of each word in a phrase. Any Idea on how to achieve it?

Example:
string str = "The food was good";
string firstLetter = "TFWG";

I use C#
.NET Framework 3.5 SP1 + Chart Controls
Visual Studio 2008
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Expert of the Quarter 2010
Expert of the Year 2010
Commented:
    string s = "abcdef asdf ga3dsf fjaf";
     string firstletter = "";
     foreach (string c in s.Split(new char[]{' '}))
     {
         firstletter += c[1];
     }
     firstletter = firstletter.ToUpper();
anarki_jimbelSenior Developer

Commented:
Very good, Kiwi! Hard to write more concise code.

One small error: should be c[0], otherwise you get all second letters: "BSAJ" (I tested :))
Expert of the Quarter 2010
Expert of the Year 2010

Commented:
Hi anarki_jimbel,

You are right.  Been working in Delphi just prior. Strings are 1-indexed there.

Cheers
Senior Developer
Commented:
There is one more flaw in the code. If you have spaces at the beginning or at the end - you will have an exeception as at least one of entries will be an empty string...

See the solution
        private void button1_Click(object sender, EventArgs e)
        {
            string s = " abcdef asdf ga3dsf fjaf ";
            string firstletters = "";
            foreach (string c in s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
            {
                firstletters += c[0];
            }
            firstletters = firstletters.ToUpper();
            MessageBox.Show("'" + firstletters + "'");
        }

Open in new window

Commented:
anarki's solution looks like it would work, here's one that works for any type of whitespace that separates words, and is slightly more efficient by using the StringBuilder to concatenate the first letter characters


string s = " the food was good";
            StringBuilder firstletters = new StringBuilder();
            foreach (string c in s.Split(new string[] {" ", "\t", "\n", "\n\r"}, StringSplitOptions.RemoveEmptyEntries))
            {
                firstletters.Append(c[0].ToUpper());
            }

            MessageBox.Show(firstletters.ToString());

Open in new window

Expert of the Quarter 2010
Expert of the Year 2010

Commented:
private void button7_Click(object sender, EventArgs e)
 {
     string s = " abcdef asdf ga,3dsf fj-af .";
     string firstletter = "";
     foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(s, @"\b(\w|['-])+\b"))
     {
         firstletter += m.Value[0].ToString().ToUpper();
     }
     MessageBox.Show(firstletter);
 }
Expert of the Quarter 2010
Expert of the Year 2010

Commented:
The RegEx captures each "word" defined as "alpha+numeric+underscore+hyphen+apostrophe"
e.g.
o'clock
non-word
made2fit

For each word matched, take the uppercased first letter.
anarki_jimbelSenior Developer

Commented:
First of all, this is not mine solution! :)
It's cyberkiwi solution, I just made some minor improvements.

Honestly, I like the original one, not with StringBuilder, not with regex. Both are overkill, I believe.
From my experience, StringBuilder works well enough for number of concatenated strings at least 20+. Too big overhead. Same for regex

Commented:
All solutions work well :), whats overkill depends on how its used and whats needed.  I think StringBuilder is better for larger usage because many separate string objects in memory isn't a good thing, faster garbage collection, etc.

Sorry cyberwiki, didn't mean to not give you credit there; should've said cyberwiki's solution and anarki's change work well.
Expert of the Quarter 2010
Expert of the Year 2010

Commented:
No disrespect and I certainly use SB a lot, but I don't bother with StringBuilder when the strings involved here are
1-char, 2-char ending up with probably 10-char?  Unless it is dealing with volumes of text.

I thought a space-based function would do, but since a more complicated solution was posed, I thought I'd post a more complete one.
anarki_jimbelSenior Developer

Commented:
Some alternative solutions are possible - faster than string concatenation or string builder. Just loop through the string, find spaces, add character after spaces to a list (array) then call new string(char  chars).
But it would be tedious to write such a function, today we don't much care about processing - processors too fast :)

Author

Commented:
I thank everybody for helping me with this.

I've awarded points to faisall, anarki_jimbel and cyberwiki. The last one got more points though I used that exact solution and it worked perfect to me.

Thanks :D