Taking first letter from each word

How would you go around to collect the first letter of each word in a string, as in to receive an abbreviation?

Input: "Java Script Object Notation"

Output: "JSON"

Penny Liu's user avatar

Penny Liu

14.5k5 gold badges77 silver badges93 bronze badges

asked Nov 26, 2011 at 16:32

Gerben Jacobs's user avatar

Gerben JacobsGerben Jacobs

4,4753 gold badges33 silver badges54 bronze badges

I think what you’re looking for is the acronym of a supplied string.

var str = "Java Script Object Notation";
var matches = str.match(/b(w)/g); // ['J','S','O','N']
var acronym = matches.join(''); // JSON

console.log(acronym)

Note: this will fail for hyphenated/apostrophe’d words Help-me I'm Dieing will be HmImD. If that’s not what you want, the split on space, grab first letter approach might be what you want.

Here’s a quick example of that:

let str = "Java Script Object Notation";
let acronym = str.split(/s/).reduce((response,word)=> response+=word.slice(0,1),'')

console.log(acronym);

answered Nov 26, 2011 at 16:35

BotNet's user avatar

4

I think you can do this with

'Aa Bb'.match(/bw/g).join('')

Explanation: Obtain all /g the alphanumeric characters w that occur after a non-alphanumeric character (i.e: after a word boundary b), put them on an array with .match() and join everything in a single string .join('')


Depending on what you want to do you can also consider simply selecting all the uppercase characters:

'JavaScript Object Notation'.match(/[A-Z]/g).join('')

answered Nov 26, 2011 at 16:36

hugomg's user avatar

hugomghugomg

67.8k24 gold badges160 silver badges246 bronze badges

4

Easiest way without regex

var abbr = "Java Script Object Notation".split(' ').map(function(item){return item[0]}).join('');

answered Apr 3, 2015 at 6:23

Almis's user avatar

AlmisAlmis

3,6192 gold badges26 silver badges58 bronze badges

This is made very simple with ES6

string.split(' ').map(i => i.charAt(0))               //Inherit case of each letter
string.split(' ').map(i => i.charAt(0)).toUpperCase() //Uppercase each letter
string.split(' ').map(i => i.charAt(0)).toLowerCase() //lowercase each letter

This ONLY works with spaces or whatever is defined in the .split(' ') method

ie, .split(', ') .split('; '), etc.

string.split(' ') .map(i => i.charAt(0)) .toString() .toUpperCase().split(',')

maxshuty's user avatar

maxshuty

9,30313 gold badges62 silver badges75 bronze badges

answered Oct 1, 2018 at 15:42

Aaron Taddiken's user avatar

2

To add to the great examples, you could do it like this in ES6

const x = "Java Script Object Notation".split(' ').map(x => x[0]).join('');
console.log(x);  // JSON

and this works too but please ignore it, I went a bit nuts here :-)

const [j,s,o,n] = "Java Script Object Notation".split(' ').map(x => x[0]);
console.log(`${j}${s}${o}${n}`);

answered May 16, 2017 at 21:51

Darryl Hebbes's user avatar

Darryl HebbesDarryl Hebbes

9581 gold badge9 silver badges15 bronze badges

@BotNet flaw:
i think i solved it after excruciating 3 days of regular expressions tutorials:

==> I’m a an animal

(used to catch m of I’m) because of the word boundary, it seems to work for me that way.

/(s|^)([a-z])/gi

answered Apr 15, 2017 at 13:51

tomersss2's user avatar

0

It’s important to trim the word before splitting it, otherwise, we’d lose some letters.

const getWordInitials = (word: string): string => {
  const bits = word.trim().split(' ');
  return bits
    .map((bit) => bit.charAt(0))
    .join('')
    .toUpperCase();
};

$ getWordInitials("Java Script Object Notation")

$ «JSON»

answered May 27, 2022 at 10:24

exaucae's user avatar

exaucaeexaucae

1,7651 gold badge11 silver badges23 bronze badges

Try —

var text = '';
var arr = "Java Script Object Notation".split(' ');
for(i=0;i<arr.length;i++) {
    text += arr[i].substr(0,1)
}    
alert(text);

Demo — http://jsfiddle.net/r2maQ/

answered Nov 26, 2011 at 16:37

ipr101's user avatar

ipr101ipr101

24k7 gold badges58 silver badges61 bronze badges

Using map (from functional programming)

'use strict';

function acronym(words)
{
    if (!words) { return ''; }

    var first_letter = function(x){ if (x) { return x[0]; } else { return ''; }};

    return words.split(' ').map(first_letter).join('');
}

answered Dec 8, 2015 at 11:26

Ben Sarah Golightly's user avatar

Alternative 1:

you can also use this regex to return an array of the first letter of every word

/(?<=(s|^))[a-z]/gi

(?<=(s|^)) is called positive lookbehind which make sure the element in our search pattern is preceded by (s|^).


so, for your case:

// in case the input is lowercase & there's a word with apostrophe

const toAbbr = (str) => {
  return str.match(/(?<=(s|^))[a-z]/gi)
            .join('')
            .toUpperCase();
};

toAbbr("java script object notation"); //result JSON

(by the way, there are also negative lookbehind, positive lookahead, negative lookahead, if you want to learn more)


Alternative 2:

match all the words and use replace() method to replace them with the first letter of each word and ignore the space (the method will not mutate your original string)

// in case the input is lowercase & there's a word with apostrophe    

const toAbbr = (str) => {
  return str.replace(/(S+)(s*)/gi, (match, p1, p2) => p1[0].toUpperCase());
};

toAbbr("java script object notation"); //result JSON

// word = not space = S+ = p1 (p1 is the first pattern)
// space = s* = p2 (p2 is the second pattern)

answered Jul 21, 2018 at 14:42

Fatma Nabilla's user avatar

Fatma NabillaFatma Nabilla

1,2711 gold badge9 silver badges7 bronze badges

How about this:

var str = "", abbr = "";
str = "Java Script Object Notation";
str = str.split(' ');
for (i = 0; i < str.length; i++) {
    abbr += str[i].substr(0,1);
}
alert(abbr);

Working Example.

answered Nov 26, 2011 at 16:36

Madara's Ghost's user avatar

Madara’s GhostMadara’s Ghost

171k50 gold badges264 silver badges309 bronze badges

1

If you came here looking for how to do this that supports non-BMP characters that use surrogate pairs:

initials = str.split(' ')
              .map(s => String.fromCodePoint(s.codePointAt(0) || '').toUpperCase())
              .join('');

Works in all modern browsers with no polyfills (not IE though)

answered Jun 4, 2020 at 10:30

James's user avatar

JamesJames

24.4k13 gold badges82 silver badges129 bronze badges

Getting first letter of any Unicode word in JavaScript is now easy with the ECMAScript 2018 standard:

/(?<!p{L}p{M}*)p{L}/gu

This regex finds any Unicode letter (see the last p{L}) that is not preceded with any other letter that can optionally have diacritic symbols (see the (?<!p{L}p{M}*) negative lookbehind where p{M}* matches 0 or more diacritic chars). Note that u flag is compulsory here for the Unicode property classes (like p{L}) to work correctly.

To emulate a fully Unicode-aware b, you’d need to add a digit matching pattern and connector punctuation:

/(?<!p{L}p{M}*|[p{N}p{Pc}])p{L}/gu

It works in Chrome, Firefox (since June 30, 2020), Node.js, and the majority of other environments (see the compatibility matrix here), for any natural language including Arabic.

Quick test:

const regex = /(?<!p{L}p{M}*)p{L}/gu;
const string = "Żerard Łyżwiński";
// Extracting
console.log(string.match(regex));                        // => [ "Ż", "Ł" ]
// Extracting and concatenating into string
console.log(string.match(regex).join(""))                // => ŻŁ
// Removing
console.log(string.replace(regex, ""))                   // => erard yżwiński
// Enclosing (wrapping) with a tag
console.log(string.replace(regex, "<span>$&</span>"))    // => <span>Ż</span>erard <span>Ł</span>yżwiński

console.log("_Łukasz 1Żukowski".match(/(?<!p{L}p{M}*|[p{N}p{Pc}])p{L}/gu)); // => null

answered Jul 3, 2020 at 12:21

Wiktor Stribiżew's user avatar

Wiktor StribiżewWiktor Stribiżew

601k37 gold badges427 silver badges539 bronze badges

In ES6:

function getFirstCharacters(str) {
  let result = [];

  str.split(' ').map(word => word.charAt(0) != '' ? result.push(word.charAt(0)) : '');
  
  return result;
}

const str1 = "Hello4 World65 123 !!";
const str2 = "123and 456 and 78-1";
const str3 = " Hello World    !!";

console.log(getFirstCharacters(str1));
console.log(getFirstCharacters(str2));
console.log(getFirstCharacters(str3));

Output:

[ ‘H’, ‘W’, ‘1’, ‘!’ ]

[ ‘1’, ‘4’, ‘a’, ‘7’ ]

[ ‘H’, ‘W’, ‘!’ ]

Dharman's user avatar

Dharman

29.9k22 gold badges82 silver badges132 bronze badges

answered Nov 5, 2021 at 8:02

Sinh Nguyễn Đức's user avatar

This should do it.

var s = "Java Script Object Notation",
    a = s.split(' '),
    l = a.length,
    i = 0,
    n = "";

for (; i < l; ++i)
{
    n += a[i].charAt(0);
}

console.log(n);

dyoo's user avatar

dyoo

11.7k1 gold badge33 silver badges44 bronze badges

answered Nov 26, 2011 at 16:36

JesseBuesking's user avatar

JesseBueskingJesseBuesking

6,4584 gold badges43 silver badges89 bronze badges

The regular expression versions for JavaScript is not compatible with Unicode on older than ECMAScript 6, so for those who want to support characters such as «å» will need to rely on non-regex versions of scripts.

Event when on version 6, you need to indicate Unicode with u.

More details: https://mathiasbynens.be/notes/es6-unicode-regex

answered Oct 22, 2015 at 13:56

SondreB's user avatar

SondreBSondreB

7986 silver badges14 bronze badges

Yet another option using reduce function:

var value = "Java Script Object Notation";

var result = value.split(' ').reduce(function(previous, current){
    return {v : previous.v + current[0]};
},{v:""});


$("#output").text(result.v);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="output"/>

answered May 18, 2016 at 8:01

Vadim Gremyachev's user avatar

Vadim GremyachevVadim Gremyachev

57.4k20 gold badges129 silver badges191 bronze badges

This is similar to others, but (IMHO) a tad easier to read:

const getAcronym = title =>
  title.split(' ')
    .map(word => word[0])
    .join('');

answered Sep 20, 2019 at 12:12

ihake's user avatar

ihakeihake

1,7311 gold badge17 silver badges29 bronze badges

ES6 reduce way:

const initials = inputStr.split(' ').reduce((result, currentWord) => 
    result + currentWord.charAt(0).toUpperCase(), '');
alert(initials);

answered Jan 16, 2020 at 9:34

user3818229's user avatar

user3818229user3818229

1,4972 gold badges19 silver badges44 bronze badges

Try This Function

const createUserName = function (name) {
const username = name
    .toLowerCase()
    .split(' ')
    .map((elem) => elem[0])
    .join('');

    return username;
};

console.log(createUserName('Anisul Haque Bhuiyan'));

answered Mar 1, 2022 at 1:32

String str is given which contains lowercase English letters and spaces. It may contain multiple spaces. Get the first letter of every word and return the result as a string. The result should not contain any space.

Examples: 

Input : str = "geeks for geeks"
Output : gfg

Input : str = "geeks for geeks""
Output : hc

Source: https://www.geeksforgeeks.org/amazon-interview-set-8-2/

The idea is to traverse each character of string str and maintain a boolean variable, which was initially set as true. Whenever we encounter space we set the boolean variable is true. And if we encounter any character other than space, we will check the boolean variable, if it was set as true as copy that charter to the output string and set the boolean variable as false. If the boolean variable is set false, do nothing. 

Algorithm: 

1. Traverse string str. And initialize a variable v as true.
2. If str[i] == ' '. Set v as true.
3. If str[i] != ' '. Check if v is true or not.
   a) If true, copy str[i] to output string and set v as false.
   b) If false, do nothing.

Implementation:

C++

#include<bits/stdc++.h>

using namespace std;

string firstLetterWord(string str)

{

    string result = "";

    bool v = true;

    for (int i=0; i<str.length(); i++)

    {

        if (str[i] == ' ')

            v = true;

        else if (str[i] != ' ' && v == true)

        {

            result.push_back(str[i]);

            v = false;

        }

    }

    return result;

}

int main()

{

    string str = "geeks for geeks";

    cout << firstLetterWord(str);

    return 0;

}

Java

class GFG

{

    static String firstLetterWord(String str)

    {

        String result = "";

        boolean v = true;

        for (int i = 0; i < str.length(); i++)

        {

            if (str.charAt(i) == ' ')

            {

                v = true;

            }

            else if (str.charAt(i) != ' ' && v == true)

            {

                result += (str.charAt(i));

                v = false;

            }

        }

        return result;

    }

    public static void main(String[] args)

    {

        String str = "geeks for geeks";

        System.out.println(firstLetterWord(str));

    }

}

Python 3

def firstLetterWord(str):

    result = ""

    v = True

    for i in range(len(str)):

        if (str[i] == ' '):

            v = True

        elif (str[i] != ' ' and v == True):

            result += (str[i])

            v = False

    return result

if __name__ == "__main__":

    str = "geeks for geeks"

    print(firstLetterWord(str))

C#

using System;

class GFG

{

    static String firstLetterWord(String str)

    {

        String result = "";

        bool v = true;

        for (int i = 0; i < str.Length; i++)

        {

            if (str[i] == ' ')

            {

                v = true;

            }

            else if (str[i] != ' ' && v == true)

            {

                result += (str[i]);

                v = false;

            }

        }

        return result;

    }

    public static void Main()

    {

        String str = "geeks for geeks";

        Console.WriteLine(firstLetterWord(str));

    }

}

Javascript

<script>

    function firstLetterWord(str)

    {

        let result = "";

        let v = true;

        for (let i = 0; i < str.length; i++)

        {

            if (str[i] == ' ')

            {

                v = true;

            }

            else if (str[i] != ' ' && v == true)

            {

                result += (str[i]);

                v = false;

            }

        }

        return result;

    }

    let str = "geeks for geeks";

      document.write(firstLetterWord(str));

</script>

Time Complexity: O(n)
Auxiliary space: O(1). 

Approach 1 : Reverse Iterative Approach 

This is simplest approach to to getting first letter of every word of the string. In this approach we are using reverse iterative loop to get letter of words. If particular letter ( i ) is 1st letter of word or not is can be determined by checking pervious character that is (i-1). If the pervious letter is space (‘ ‘) that means (i+1) is 1st letter then we simply add that letter to the string. Except character at 0th position. At the end we simply reverse the string and function will return string which contain 1st letter of word of the string.

C++

#include <iostream>

using namespace std;

void get(string s)

{

    string str = "", temp = "";

    for (int i = s.length() - 1; i > 0; i--) {

        if (isalpha(s[i]) && s[i - 1] == ' ') {

            temp += s[i];

        }

    }

    str += s[0];

    for (int i = temp.length() - 1; i >= 0; i--) {

        str += temp[i];

    }

    cout << str << endl;

}

int main()

{

    string str = "geeks for geeks";

    string str2 = "Code of the    Day";

    get(str);

    get(str2);

    return 0;

}

Java

public class GFG {

    public static void get(String s)

    {

        String str = "", temp = "";

        for (int i = s.length() - 1; i > 0; i--) {

            if (Character.isLetter(s.charAt(i))

                && s.charAt(i - 1) == ' ') {

                temp

                    += s.charAt(i);

            }

        }

        str += s.charAt(0);

        for (int i = temp.length() - 1; i >= 0; i--) {

            str += temp.charAt(i);

        }

        System.out.println(str);

    }

    public static void main(String[] args)

    {

        String str = "geeks for geeks";

        String str2 = "Code of the    Day";

        get(str);

        get(str2);

    }

}

Python3

def get(s):

    str = ""

    temp = ""

    for i in range(len(s)-1, 0, -1):

        if s[i].isalpha() and s[i-1] == ' ':

            temp += s[i]

    str += s[0]

    for i in range(len(temp)-1, -1, -1):

        str += temp[i]

    print(str)

str = "geeks for geeks"

str2 = "Code of the    Day"

get(str)

get(str2)

Javascript

function get(s) {

  let str = "", temp = "";

  for (let i = s.length - 1; i > 0; i--) {

    if (s[i].match(/[a-zA-Z]/) && s[i - 1] === ' ') {

      temp += s[i];

    }

  }

  str += s[0];

  for (let i = temp.length - 1; i >= 0; i--) {

    str += temp[i];

  }

  console.log(str);

}

const str = "geeks for geeks";

const str2 = "Code of the    Day";

get(str);

get(str2);

Time Complexity: O(n)
Auxiliary space: O(1). 

Approach 2: Using StringBuilder

This approach uses the StringBuilder class of Java. In this approach, we will first split the input string based on the spaces. The spaces in the strings can be matched using a regular expression. The split strings are stored in an array of strings. Then we can simply append the first character of each split string in the String Builder object.  

Implementation:

C++

#include <bits/stdc++.h>

using namespace std;

string processWords(char *input)

{

    char *p;

    vector<string> s;

    p = strtok(input, " ");

    while (p != NULL)

    {

        s.push_back(p);

        p = strtok(NULL, " ");

    }

    string charBuffer;

    for (string values : s)

        charBuffer += values[0];

    return charBuffer;

}

int main()

{

    char input[] = "geeks for geeks";

    cout << processWords(input);

    return 0;

}

Java

class GFG

{

   private static StringBuilder charBuffer = new StringBuilder();

   public static String processWords(String input)

   {

        String s[] = input.split("(\s)+");

        for(String values : s)

        {

            charBuffer.append(values.charAt(0));

        }

      return charBuffer.toString();

   }

   public static void main (String[] args)

   {

      String input = "geeks for geeks";

      System.out.println(processWords(input));

   }

}

Python3

charBuffer = []

def processWords(input):

    s = input.split(" ")

    for values in s:

        charBuffer.append(values[0])

    return charBuffer

if __name__ == '__main__':

    input = "geeks for geeks"

    print(*processWords(input), sep = "")

C#

using System;

using System.Text;

class GFG

{

private static StringBuilder charBuffer = new StringBuilder();

public static String processWords(String input)

{

        String []s = input.Split(' ');

        foreach(String values in s)

        {

            charBuffer.Append(values[0]);

        }

    return charBuffer.ToString();

}

public static void Main()

{

    String input = "geeks for geeks";

    Console.WriteLine(processWords(input));

}

}

Javascript

<script>

var charBuffer = "";

function processWords(input)

{

        var s = input.split(' ');

        s.forEach(element => {

            charBuffer+=element[0];

        });

    return charBuffer;

}

var input = "geeks for geeks";

document.write( processWords(input));

</script>

Time Complexity: O(n)
Auxiliary space: O(1). 

Another Approach: Using boundary checker, refer https://www.geeksforgeeks.org/get-first-letter-word-string-using-regex-java/

This article is contributed by Aarti_Rathi and Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

This post will guide you how to extract first letter from each word in a given cell in Excel. How do I extract the first letter of each word in a range of names in your current worksheet in Microsoft Excel 2013/2016. Assume that you have a range of First, Second and third names and you would like to extract the initials to a separate cell.

For example, one name called “Nigolas Kate”, and you want to extract the first letters so that the result would be “NK”.

extract first letter from word1

Table of Contents

  • 1. Extract First Letter from Each Word in a Cell Using User Defined Function with VBA
  • 2. Extract First Letter from Each Word in a Cell Using Formula
  • 3. Video: Extract First Letter from Each Word in a Cell in Excel

Since there is not built-in function to extract the first letter of each word in Excel, and you can define a user defined function by Excel VBA code to achieve the result. Just do the following steps:

Step1: open your excel workbook and then click on “Visual Basic” command under DEVELOPER Tab, or just press “ALT+F11” shortcut.

Get the position of the nth using excel vba1

Step2: then the “Visual Basic Editor” window will appear.

Step3: click “Insert” ->”Module” to create a new module.

convert column number to letter3

Step4: paste the below VBA code into the code window. Then clicking “Save” button.

Function ExtractFirstLetter(text) As String
    mystring = Left(text, 1)
    For i = 2 To Len(text) - 1
        If Mid(text, i, 1) = " " Then
            mystring = mystring & Mid(text, i + 1, 1)
        End If
    Next i

    ExtractFirstLetter = WorksheetFunction.Substitute(UCase(mystring), " ", "")
End Function

extract first letter from word2

Step5: back to the current worksheet, then type the following formula in a blank cell, and then press Enter key.

=ExtractFirstLetter(A1)

extract first letter from word3

If you want to extract the first letter from each word in a cell in Excel, you can use a combination of the CONCATENATE, LEFT, MID and FIND functions and return them as a concatenated string.

You need to enter the following formula in a blank cell:

=CONCATENATE(LEFT(A1,1),MID(A1,FIND(" ",A1)+1,1),IFERROR(MID(A1,FIND(" ",A1,FIND(" ",A1)+1)+1,1),""))

Press Enter to apply the formula.

You can then copy and paste the formula to apply it to other cells, or drag the fill handle to apply it to a range of cells.

Here’s how this formula works:

The LEFT function is used to extract the first letter of the first word in the cell.

The MID and FIND functions are used to extract the first letter of the second and subsequent words in the cell.

The CONCATENATE function is used to join the first letters of each word in the cell.

The IFERROR function is used to handle cells with only one or two words. If the cell has only one or two words, the formula returns the first letter of those words.

If you want to learn how to extract the first letter from each word in a cell in Excel, you can watch this video that shows you how to use a formula or a VBA code to achieve this task.

$begingroup$

Shrink each word in a string of group of strings to single letters delineated by spaces or punctuation.

Example

I'm a little teapot,  short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout!   Tip me over and pour me out. 

becomes

I' a l t, s a s. H i m h, h i m s. W I g a s u - h m s! T m o a p m o. 

Edit — if there are multiple spaces, preserve only one space. All punctuation should be preserved, I missed the apostrophe. Yes this is code golf :-).

jimmy23013's user avatar

jimmy23013

36.6k6 gold badges74 silver badges144 bronze badges

asked May 24, 2015 at 20:49

Cthanatos's user avatar

$endgroup$

11

$begingroup$

CJam, 13 bytes

r{('A,f&Sr}h

Works if I can consider only the common punctuation characters, and the output can have trailing spaces. (Thanks to Dennis.)

This question needs much more clarification…

CJam, 17 16 bytes

r{(eu_elf&Sr}h&

Try it online.

Explanation

r          e# Read one word from input.
{          e# While it is not EOF:
    (     e# Extract the first character.
    eu     e# Convert the rest to uppercase.
    _el    e# And lowercase.
    f&     e# Delete characters in the first string if not in the second string.
    S      e# Append a space.
    r      e# Read the next word.
}h
&          e# Discard the last space by intersecting with empty string.

Community's user avatar

answered May 24, 2015 at 21:16

jimmy23013's user avatar

jimmy23013jimmy23013

36.6k6 gold badges74 silver badges144 bronze badges

$endgroup$

6

$begingroup$

Pyth, 14 bytes

jdm+hd-rtd0Gcz

Try it online: Demonstration

Explanation:

                 implicit: z = input string
            cz   split z by spaces
  m              map each word d to:
    hd              first letter of d
   +                +
       rtd0         (lowercase of d[1:]
      -    G         but remove all chars of "abc...xyz")
jd               join resulting list by spaces and print

answered May 24, 2015 at 21:18

Jakube's user avatar

JakubeJakube

21.8k3 gold badges25 silver badges108 bronze badges

$endgroup$

5

$begingroup$

Python 3.4, 94 92 82 77 bytes

print(*[w[0]+''.join(c[c.isalpha():]for c in w[1:])for w in input().split()])

I’m new to code golfing but I thought I’d give it a try! This one’s not a winner, but it was fun.

This just splits the string, taking the first character of each word along with any punctuation in the rest of the word.

*edited with changes by FryAmTheEggman, DLosc

answered May 24, 2015 at 23:14

Robotato's user avatar

$endgroup$

4

$begingroup$

sed (39 chars)

Just a couple of regular expressions:

sed 's+<(.)[A-Za-z]*+1+g;s+  *+ +g'

answered May 25, 2015 at 0:53

joeytwiddle's user avatar

joeytwiddlejoeytwiddle

6213 silver badges8 bronze badges

$endgroup$

1

$begingroup$

Lua — 126 characters

Lua isn’t much of a code golfing language, but I gave it a shot:

a=''for b in string.gmatch( c, '%S+%s?' )do d=(b:match('%w')or''):sub(1,1)e=b:match('[^%s%w]')or''a=a..d..e..' 'end print( a )

This assumes that c is the string.

Here it is cleaned up for readability:

local string = [[I'm a little teapot,  short and stout. Here is my handle, here is my 
spout. When I get all steamed up - hear me shout!   Tip me over and pour me out.]]

local final = ''
for word in string.gmatch( string, '%S+%s?' ) do 
    local first = ( word:match( '%w' ) or '' ):sub( 1, 1 )
    local second = word:match( '[^%s%w]' ) or ''
    final = final .. first .. second .. ' '
end
print( final )

You can test it here (copy and paste it. For the first on you also have to do c = "I'm a little ....)
For some reason the online demo of Lua won’t let you input variables using io.read

answered May 25, 2015 at 2:21

DavisDude's user avatar

DavisDudeDavisDude

2731 silver badge9 bronze badges

$endgroup$

$begingroup$

PowerShell, 56 bytes

%{($_-split' '|%{$_[0]+($_-replace'[a-z]','')})-join' '}

answered May 25, 2015 at 2:10

Nacht's user avatar

NachtNacht

4812 silver badges5 bronze badges

$endgroup$

$begingroup$

Javascript (ES6) 72 68 bytes

f=x=>x.split(/s+/).map(x=>x.replace(/^(.)|[a-z]/gi,'$1')).join(' ')
<input id="input" value="I'm a little teapot,  short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout!   Tip me over and pour me out. " />
<button onclick="output.innerHTML=f(input.value)">Run</button>
<br /><pre id="output"></pre>

Commented:

f=x=>
    x.split(/s+/). // split input string by 1 or more spaces
    map(x=> // map function to resulting array
        x.replace(/^(.)|[a-z]/gi, '$1') // capture group to get the first character
                                        // replace all other letters with empty string
    ).
    join(' ') // join array with single spaces

answered May 25, 2015 at 1:53

nderscore's user avatar

nderscorenderscore

4,96014 silver badges38 bronze badges

$endgroup$

$begingroup$

C99 — 170 169 bytes

main(_,a)char**a;{for(char*b=a[1],*c=b,*e,*d;*c++=*b;){for(e=b;*++b&&*b-32;);for(*b=0,d=strpbrk(e,"!',-."),d&&d-e?*c++=*d:0;b[1]==32;++b);++b;*c++=32;*c=0;}puts(a[1]);}

Ungolfed:

main(int argc, char**a) {
    char*b=a[1],*c=b,*e,*d;
    while(*c++=*b){
        for(e=b;*++b&&*b-32;); //scan for first space or end of word
        *b=0; //mark end of word
        for(;b[1]==32;++b); //skip following spaces
        d=strpbrk(e,"!',-."); //find punctuation
        if(d&&d-e) //append punctuation if any, and it's not the word itself
            *c++=*d;
        *c++=32; //append space
        b++;
    }
    *c=0; //mark end of line
    puts(a[1]);
}

Usage:

gcc -std=c99 test.c -o test
./test "I'm a little teapot,  short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout!   Tip me over and pour me out."

Output:

I' a l t, s a s. H i m h, h i m s. W I g a s u - h m s! T m o a p m o.

Optimizer's user avatar

Optimizer

26.5k7 gold badges64 silver badges141 bronze badges

answered May 25, 2015 at 8:14

rr-'s user avatar

rr-rr-

2831 silver badge5 bronze badges

$endgroup$

$begingroup$

Java 8, 87 bytes

s->{for(String x:s.split(" +"))System.out.print(x.replaceAll("^(.)|[a-z]+","$1")+" ");}

Explanation:

Try it here.

s->{                                  // Method with String parameter and no return-type
  for(String x:s.split(" +"))         //  Split the input on one or multiple spaces
                                      //  And loop over the substrings
    System.out.print(                 //   Print:
      x.replaceAll("^(.)|[a-z]+","$1")//    Regex to get the first letter + all non-letters
      +" ");                          //    + a space delimiter
                                      //  End of loop (implicit / single-line body)
}                                     // End of method

Regex explanation:

x.replaceAll("^(.)|[a-z]+","$1")
x.replaceAll("           ","  ") # Replace the match of String1 with String2, in String `x`
             "           "       # Regex to match:
              ^(.)               #  The first character of String `x`
                  |[a-z]+        #  Or any one or multiple lowercase letters
                           "  "  # Replace with:
                            $1   #  The match of the capture group (the first character)

So it basically removes all lowercase letters of a String, except the very first one.

Community's user avatar

answered Oct 20, 2017 at 6:59

Kevin Cruijssen's user avatar

Kevin CruijssenKevin Cruijssen

117k10 gold badges133 silver badges359 bronze badges

$endgroup$

$begingroup$

Perl 5, 34 bytes

33 bytes code + 1 for -p.

s!SKS+| K +!$&=~s/w| //gr!ge

Try it online!

answered Oct 20, 2017 at 10:01

Dom Hastings's user avatar

Dom HastingsDom Hastings

22.8k3 gold badges49 silver badges90 bronze badges

$endgroup$

$begingroup$

R, 46 45 bytes

cat(gsub("^\w\W*\K\w*","",scan(,""),T,T))

This reads a line from STDIN and prints to STDOUT. It uses a regular expression to remove all characters after the first letter followed by any amount of punctuation.

Ungolfed + explanation:

# Read a string from STDIN and convert it to a character vector,
# splitting at spaces

input <- scan(what = "")

# Replace stuff with nothing using a regex.
# ^ start position anchor
# w single "word" character
# W* any amount of non-word (i.e. punctuation) characters
# K move the match position forward
# w* any number of word characters

replaced <- gsub("^\w\W*\K\w*", "", input, ignore.case = TRUE, perl = TRUE)

# Print the vector elements to STDOUT, separated by a space

cat(replaced, sep = " ")

Example:

> cat(gsub("^\w\W*\K\w*","",scan(,""),T,T))
1: I'm a little teapot,  short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout!   Tip me over and pour me out. 

I' a l t, s a s. H i m h, h i m s. W I g a s u - h m s! T m o a p m o.

answered May 25, 2015 at 18:04

Alex A.'s user avatar

Alex A.Alex A.

24.5k5 gold badges36 silver badges118 bronze badges

$endgroup$

$begingroup$

05AB1E, 13 bytes

#õKεćsDáмJ}ðý

Try it online!

Explanation:

#õKεćsDáмJ}ðý  Full program
#              Split on spaces
 õK            Remove empty strings from the list
   ε           For each...
    ć             push a[1:], a[0]
     s            Swap
      D           Duplicate
       á          Push only letters of a
        м         pop a,b => push a.remove(all elements of b)
         J        Join
          }    End for each
           ðý  Join with spaces

answered Oct 19, 2017 at 19:02

scottinet's user avatar

scottinetscottinet

1,0216 silver badges7 bronze badges

$endgroup$

$begingroup$

VBA (Excel), 141 133 Bytes

Using VBA Immediate Window, [A1] as Inputted Strings.

z=" "&[A1]:for a=2 to len(z):c=mid(z,a,1):[A2]=[A2]&IIF(mid(z,a-1,1)=" ",c,IIF(asc(lcase(c))>96 and asc(lcase(c))<123,"",c)):next:?[TRIM(A2)]

z=" "&[a1]:for a=2 to len(z):c=mid(z,a,1):e=asc(lcase(c)):[a2]=[a2]&iif(mid(z,a-1,1)=" ",c,IIF((e>96)*(e<123),"",c)):next:?[TRIM(A2)]

answered Oct 20, 2017 at 8:21

remoel's user avatar

remoelremoel

5113 silver badges6 bronze badges

$endgroup$

$begingroup$

Perl 6, 15 bytes

s:g/(w)w+/$0/

Try it online!

answered Oct 19, 2017 at 19:10

Massa's user avatar

MassaMassa

1896 bronze badges

$endgroup$

1

  • #1

Hi All,
Am using the formula

Code:

[COLOR=#000000][FONT=lucida grande]=LEFT(LEFT(A1,FIND(" ",A1,1)),1)&LEFT(SUBSTITUTE(A1,LEFT(A1,FIND(" ",A1,1)),""),1)&LEFT(RIGHT(A1,FIND(" ",A1,1)-1),1)[/FONT][/COLOR]

to get first letter from each word in a cell..

If Cell A1 is «Excel Forum Questions», then in B1 am getting EFQ

Need to know any simpler formula to do this….

Also, if A1 is having variable words, like «Excel Questions», then it should give only EQ

Any suggestions please….

Who is Mr Spreadsheet?

Author John Walkenbach was Mr Spreadsheet until his retirement in June 2019.

  • #2

Maybe slightly simpler, but not much . . .

Code:

=LEFT(A1,1)&MID(A1,FIND(" ",A1&" ",1)+1,1)&MID(A1&"  ",FIND(" ",A1&"  ",FIND(" ",A1&" ",1)+1)+1,1)

Returns EQ as specified.

Note, the [A1&» «] sections are important for dealing with shorter text examples, and the number of spaces between the » characters gradually increments. Post back if this doesn’t make sense.

  • #3

I’m not getting the same results with your formula,at least as posted.

How about a UDF?
The code below works for me in testing, it pulls the 1st letter of the string then any other characters that follow a space. It could be further tweaked to dissallow numbers & other non-letter characters from being pulled, but this works for your own examples.

Code:

Function PullFirstLetters(text) As String
'extract the first letters of each word in a sentence or string

mystring = Left(text, 1)

For i = 2 To Len(text) - 1
If Mid(text, i, 1) = " " Then
    mystring = mystring & Mid(text, i + 1, 1)
End If

Next i

PullFirstLetters = WorksheetFunction.Substitute(UCase(mystring), " ", "")
End Function

  • #4

I’m not getting the same results with your formula,at least as posted.

Did you copy and paste it ? Or type it in manually ? If manually, perhaps you missed some space characters. I just tried it again and it seems to work for up to 3 words, and can be adapted for more.

  • #5

Sorry — I was referring to the OP’s formula.

(Your formula does work for me — at least up to 3 words which fall within the OP’s examples)

Joe4

Peter_SSs

Like this post? Please share to your friends:
  • Taking away rights word
  • Takes a lot of time word
  • Taken one s word for it
  • Taken down from the word go
  • Take your word on that meaning