Note: The winning answer will be selected on 4/12/17 the current winner is Jolf, 1 byte.

I'm surprised that we haven't had a what's my middle name challenge on this site yet. I did alot of searching but found nothing. If this is a dup, please flag it as such.

Your challenge

Parse a string that looks like Jo Jean Smith and return Jean.

Test cases

Input: Samantha Vee Hills
Output: Vee

Input: Bob Dillinger
Output: (empty string or newline)

Input: John Jacob Jingleheimer Schmidt
Output: Jacob Jingleheimer

Input: Jose Mario Carasco-Williams
Output: Mario

Input: James Alfred Van Allen
Output: Alfred Van 

(That last one is incorrect technically, but fixing that would be too hard.)

Notes:

  • Names will always have at least 2 space-separated parts, with unlimited middle names between them or can be a list/array of strings.
  • Names may contain the alphabet (case-insensitive) and - (0x2d)
  • You may output a trailing newline.
  • You may require input to have a trailing newline.
  • Input from STDIN, a function parameter, or command-line argument is allowed, but hard-coding it in is not allowed.
  • Standard loopholes forbidden.
  • Output may be function return value, STDOUT, STDERR, etc.
  • Trailing spaces/newlines/tabs in the output are allowed.
  • Any questions? Comment below!

This is , so the shortest anwser in bytes wins!

  • 2
    Can the output be a list of strings? – Anthony Pham Apr 2 '17 at 14:34
  • 5
    If other formats than a space-separated string are allowed, please edit that into the specification. – Martin Ender Apr 2 '17 at 14:46
  • 5
    @programmer5000: if the input can be a list of strings, how about the output? Is ["John", "Jacob", "Jingleheimer", "Schmidt"] -> ["Jacob", "Jingleheimer"] a valid solution? – nimi Apr 2 '17 at 15:17
  • 3
    Are leading spaces allowed? – betseg Apr 2 '17 at 15:32
  • 2
    @DJ Because "Van" isn't his middle name, it's part of his last name. A particularly vexing case is David Lloyd George, whose first name is David and last name is Lloyd George. Any attempt to parse real people's names like this is doomed. In fact, you can't even tell what the first and last names are (think Li Shi). – David Conrad Apr 3 '17 at 2:16

58 Answers 58

up vote 5 down vote accepted

Jolf, 1 byte

Gets the inside of the input. Try it here!

  • Can't seem to get the example running - nothing seems to happen when I click any of the buttons. Using Chrome 57.0.2987.133 – Yimin Rong Apr 6 '17 at 18:21
  • @YiminRong I can only assure it to work on firefox. – Conor O'Brien Apr 6 '17 at 18:57

Ohm, 2 bytes (CP437)

Accepts and returns a list of strings.

()

Explanation:

()   Main wire, arguments: a

(    Remove the first element of a
 )   ...and then the last element of that
     Implicit output

Vim, 6 5 bytes

dW$BD

Try it online!

(outputs with a trailing space)

Since Vim is reverse-compatible with V, I have included a TIO link for V.

Explanation

dW                      " Delete up to the next word (removes the first name)
$                       " Go to the end of the line
B                       " Go back one word
D                       " Delete it
  • Drat, you beat me to it. dWWD saves you one byte. – DJMcMayhem Apr 2 '17 at 14:41
  • 5
    @DJMcMayhem That only works for exactly one middle name. – Martin Ender Apr 2 '17 at 14:43
  • What's the difference between dW and dw? – Duncan X Simpson Apr 4 '17 at 0:56
  • 1
    @DuncanXSimpson dW deletes until whitespace. dw deletes until non-word characters. – Nic Hartley Apr 4 '17 at 5:52

Python, 24 bytes

lambda n:n.split()[1:-1]

Try it online string input!

Input Format: string


Python 2, 16 bytes

lambda n:n[1:-1]

Try it online list input!

Input Format: List

  • You should edit the title with Python instead of Python 2, because it works for Python 3 as well, was just about to post that. – Mr. Xcoder Apr 2 '17 at 14:51
  • @L3viathan since OP hasn't mentioned the output format must be a string, and since the input format is allowed to be a list, print a list cannot be considered as a wrong result! – Keerthana Prabhakaran Apr 2 '17 at 15:24
  • According to the comments on the question, you can both input and output a list of strings. Save a bunch of bytes lambda n:n[1:-1] – Luke Sawczak Apr 3 '17 at 17:28
  • 1
    Since you can read from STDIN, can replace the lambda with input() (Python 3 only) – BallpointBen Apr 3 '17 at 19:27
  • You are right. Thanks. I've added the edits! – Keerthana Prabhakaran Apr 4 '17 at 17:24

05AB1E, 2 bytes

¦¨

Try it online!

If outputting a list of middle names isn't allowed, I'll change it.

Brain-Flak, 133 bytes

{{}((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}}{}{({}<>)<>}<>{{}((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}}{}{({}<>)<>}<>

Try it online!

132 bytes of code, plus 1 byte for the -c flag which allows ASCII input and output.

Unfortunately, this contains lots of duplicated code, but it would be really difficult to reuse. I'll look into it later. Here's an explanation:

#While True
{
    #Pop
    {}

    #Not equals 32
    ((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}

#Endwhile
}

#Pop the 0
{}

#Reverse Stack
{({}<>)<>}<>

#While True
{
    #Pop
    {}

    #Not equals 32
    ((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}

#Endwhile
}

#Pop the 0
{}

#Reverse Stack
{({}<>)<>}<>
  • 86 bytes when you remove the comments. I added the first two and the last line. TIO – Riley Apr 2 '17 at 17:31
  • @riley Cool solution. Feel free to post it yourself! – DJMcMayhem Apr 2 '17 at 18:21

Haskell, 23, 17 9 bytes

init.tail

Takes and returns a list of strings. Try it online!

Drop first string, drop last string.

Edit: @Generic Display Name noted, that the input can be a list of strings, which saved 6 bytes.

Edit II: return list of strings instead of a single string

  • It looks like input as a list is allowed, so drop the words for -5 bytes – Generic Display Name Apr 2 '17 at 15:07
  • @GenericDisplayName: Oh, didn't notice. Thanks! – nimi Apr 2 '17 at 15:14
  • My Ohm answer and the Mathematica answer both output lists of strings as well, so you could probably drop unwords. for -8 bytes. – Nick Clifford Apr 2 '17 at 15:21
  • @NickClifford: yes, I saw that myself and asked the OP for clarification. – nimi Apr 2 '17 at 15:22

Mathematica, 10 bytes

Rest@*Most

An unnamed function that accepts and returns a list of strings.

Rest discards the the last element, Most discards the first element, @* is function composition. Swapping Rest and Most or using right-composition /* instead would also work. This beats indexing via #[[2;;-2]]& by one byte.

Brain-Flak, 86 bytes

(()()){({}[()]<{{}((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}}{}{({}<>)<>}<>>)}{}

Try it online!

Most of this code comes from this answer. If you like my solution you should upvote that one as well.

#Push 2
(()())

#Loop twice
{({}[()]<

  #While not a space
  {
      #Pop
      {}

      #Not equals 32
      ((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}

  #Endwhile
  }

  #Pop the 0
  {}

  #Reverse Stack
  {({}<>)<>}<>

#End loop twice
>)}{}
  • Well done! I didn't think about holding a counter for pushing later, so I spent too long thinking about how to loop across different stacks. – DJMcMayhem Apr 3 '17 at 16:47

Java 7, 74 bytes

String f(String s){return s.substring(s.indexOf(' '),s.lastIndexOf(' '));}

Java 8, 49 bytes

s->s.substring(s.indexOf(' '),s.lastIndexOf(' '))

Function which identifies the first occurrence of the space character and the last one and extracts the middle. The resulting string is prefixed by a space character (at the time of the posting, OP hasn't clarified if leading spaces are allowed), which can be eliminated by adding .trim() to the code for an extra cost of 7 bytes.

Compared to C#, Java has the advantage of specifying the end index instead of sub-string length, which brings down the byte count.

JavaScript (ES6), 22 bytes

Takes and outputs an array of strings.

([_,...a])=>a.pop()&&a

Test cases

let f =

([_,...a])=>a.pop()&&a

console.log(f(["Samantha", "Vee", "Hills"]))
console.log(f(["Bob", "Dillinger"]))
console.log(f(["John", "Jacob", "Jingleheimer", "Schmidt"]))
console.log(f(["Jose", "Mario", "Carasco-Williams"]))

String version (27 bytes)

Takes and outputs a string. The output string is either a single space if no middle name was found, or the middle names with leading and trailing spaces.

s=>(/ .* /.exec(s)||' ')[0]

let f =

s=>(/ .* /.exec(s)||' ')[0]

console.log(f("Samantha Vee Hills"))
console.log(f("Bob Dillinger"))
console.log(f("John Jacob Jingleheimer Schmidt"))
console.log(f("Jose Mario Carasco-Williams"))

  • /./.exec.bind(/ .* /) seems to mimic #2, except null for none – dandavis Apr 7 '17 at 6:48

AWK, 17 10 bytes

Saved 7 bytes thanks to @steve!

$NF=$1=x;1

Try it online!

Explanation:

$NF=    set last word to
$1=     set first word to
x       an empty variable, ie empty string
1       default action, ie print everything
  • Can be shaved down to 11 bytes, $NF=$1="";1 – steve Apr 2 '17 at 15:47
  • 2
    Or 10 using $NF=$1=x;1 – steve Apr 2 '17 at 15:50
  • 1
    @steve what does 1 do? I'm not so good at AWK :) – betseg Apr 2 '17 at 15:52
  • 1 just means take the default action, that is, to print $0. – steve Apr 2 '17 at 15:54

Groovy, 19 bytes

{it.split()[1..-2]}

Explanation:

{        
 it                  all closures have an implicit argument called "it"
   .split()          splits by spaces by default. Returns an array of words
           [1..-2]   take the whole array from the second index (1) to the penultimate index (-2). Implicitly return
                  }

A closure / anonymous function

  • 1
    Welcome to PPCG! Can you take a list of strings as input to skip the .split()? – Martin Ender Apr 2 '17 at 20:51
  • Martin Ender Yes, if you assume that the input will always be a list of strings then {it[1..-2]} would work. – staticmethod Apr 2 '17 at 22:12

PHP, 37 Bytes

<?=join(" ",array_slice($argv,2,-1));

-4 bytes for an output as array

print_r(array_slice($argv,2,-1));

PHP, 42 Bytes

echo trim(trim($argn,join(range("!",z))));

PHP, 50 Bytes

echo preg_filter("#(^[^\s]+ |[^\s]+$)#","",$argn);

Retina, 11 bytes

^\S+ |\S+$

Try it online!

Matches the first word (including the space after it) and the last word, and removes both of them.

If I/O can be a linefeed-separated list, it can be done in 8 bytes instead:

A1`
G-2`

Try it online!

Jelly, 2 bytes

ḊṖ

Try it online!

This works as a non-inline link (i.e. function), not a full program.

'John','Jacob','Jingleheimer','Schmidt''Jacob','Jingleheimer'

As a full program, it would be 3 bytes: ḊṖK, which prints a space-separated middle name.

Pyth, 2 bytes

Pt

Online interpreter

Perl 5, 27 18 bytes

Need to run with -n option.

/ (.+) /&&print$1

Try it online!

Wanted to do something similar in sed first, but, unfortunately, it doesn't support non-greedy quantifier. It is needed in case middle name is more than one word.

Edit

-9 bytes thanks to Dada.

Non-greedy quantifier is not needed anymore, among with some other things.

  • / (.+) /&&print$1 should be sorter. Great to see some new people golfing with Perl! – Dada Apr 2 '17 at 20:30
  • @Dada Thanks for the tip! It's actually my first time ever writing in Perl. Do you know why print if s| (.+) |\1| doesn't work? To me it looks similar to what you wrote. – Max Lawnboy Apr 2 '17 at 20:54
  • print if s| (.+) |\1| replaces the middle part with... the middle part! (minus the spaces before and after), so it doesn't work. On the other side, what I suggested only matches the middle part and print only it ($1). – Dada Apr 2 '17 at 21:00

Javascript (ES6) 49 16 bytes

Edit:

a=>a.slice(1,-1)

Try it online!

ungolfed:

function(name) {
  return a.slice(1, -1); //start at the second item and end at the second to last item
};

I forgot some of the simple properties of slice, and that the input can be an array. Thanks to @Neil and @fəˈnɛtɪk I was able to remove 27 bytes. Still not really competing.

Original:

This isn't really competing but here's a Javascript solution:

a=>{a=a.split(' ');return a.slice(1, a.length-1)}

This creates an anonymous function equal to:

function(name) {
  let name = name.split(' '); //first middle last -> [first, middle, last]
  return name.slice(1, name.length - 1); //get the second item to the second to last item in the array.
}

How I golfed it

This is a pretty simple golf. I turned the function into an arrow function. Then I "minified" the code. This included renaming name into a single character(a in this case) and removing the let decloration of the variable.

Snippet

var a=b=>b.slice(1,-1)

//example code

let form = document.querySelector('#form'),
    input = document.querySelector('#input'),
    result = document.querySelector('#result');

form.addEventListener('submit', (event) => {
  event.preventDefault();
  let value = input.value.split` `;
  result.textContent = a(value).join(' ');
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<form id="form">
  <div class="input-group">
    <input id="input" class="form-control" />
    <div class="input-group-btn">
      <button class="btn btn-primary">Submit</button>
    </div>
  </div>
</form>

<p id="result"></p>

Hope this helps anyone who is stuck on the challenge.

  • The length - is unnecessary, as slice already accepts negative lengths as being relative to the end. This means that you no longer need the intermediate variable, so you can turn your arrow function from a block into an expression. – Neil Apr 2 '17 at 23:51
  • Actually the way it works is that -1 is the last but one that you need here. – Neil Apr 3 '17 at 0:05
  • It is also slice(1,-1). slice(1,-2) removes two from the end. – fəˈnɛtɪk Apr 3 '17 at 0:14
  • You can also assume that you were passed an array to begin with, which lets you just perform slice and you are done. – fəˈnɛtɪk Apr 3 '17 at 0:21
  • I'm 99% sure that was changed since I started it. Thanks again. – David Archibald Apr 3 '17 at 0:25

Röda, 9 bytes

{_[1:-1]}

Try it online!

Not a very interesting solution. Takes a list from the stream and returns the middle names.

21 bytes and I/O:

{[(_/" ")[1:-1]&" "]}

Try it online!

This uses / (split) and & (join).

C#, 67 bytes

s=>s.Substring(s.IndexOf(' ')+1,s.LastIndexOf(' ')-s.IndexOf(' '));

Anonymous function which identifies the first occurrence of the space character and the last one and extracts the middle. It also extracts a trailing space, which can be removed at the cost of 2 bytes.

Full program with test cases:

using System;

namespace WhatsMyMiddleName
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string, string> f =
            s=>s.Substring(s.IndexOf(' ')+1,s.LastIndexOf(' ')-s.IndexOf(' '));

            Console.WriteLine(f("Jo Jean Smith"));          // "Jean"
            Console.WriteLine(f("Samantha Vee Hills"));     // "Vee"
            Console.WriteLine(f("Bob Dillinger"));          // ""
            Console.WriteLine(f("John Jacob Jingleheimer Schmidt"));// "Jacob Jingleheimer"
            Console.WriteLine(f("Jose Mario Carasco-Williams"));    // "Mario"
            Console.WriteLine(f("James Alfred Van Allen")); // "Alfred Van"
        }
    }
}

Kotlin, 39 bytes

s.filterIndexed{i,j->i!=0&&i!=s.size-1}

Try it online!

i.e.

s.filterIndexed{ index, value -> index != 0 && index != (s.size - 1) }

VBA, 69 bytes

Sub m(n)
f=InStr(1,n," ")
Debug.?Mid(n,f+1,InStrRev(n," ")-f)
End Sub

R, 30 27 22 bytes

Current solution due to user11599!

head(scan(,''),-1)[-1]

Takes input from stdin, returns each middle name as a separate string. Returns character() in the case of no middle name; that is, a vector of class character of length 0.

Explanation:

Read stdin into a list of strings, separated by spaces

     scan(,'')

Remove the last element. head returns the first n elements of a list, with n defaulting to 6. If n is -1 it returns all but the last element.

head(scan(,''),-1)

Now, remove the first element of this list.

head(scan(,''),-1)[-1]

This yields the middle name(s).

  • 1
    Even shorter: head(scan(,''),-1)[-1] 22 bytes. Note that '' are two single quotes. – user11599 Apr 4 '17 at 6:29
  • If you don't want each name quoted, use, at 27 bytes, cat(head(scan(,''),-1)[-1]) – user11599 Apr 4 '17 at 6:36
  • Explanation: scan(,'') breaks the string into words, head(...,-1) drops the last word, head(...,-1)[-1] then drops the first word, cat() formats the output dropping the quotes. For no middle name, result isn't perfect, it's character(0), the empty string. – user11599 Apr 4 '17 at 6:48
  • @user11599 Wow, thanks! I had played around with head() and tail(), but I didn't know you could pass a negative number as the second argument. Nice! – rturnbull Apr 4 '17 at 8:39
  • Your use of scan(,'') inspired me. I didn't think of approaching that way. – user11599 Apr 4 '17 at 9:03

Ruby, 24 13 bytes

p ARGV[1..-2]

Saved 11 bytes thanks to Piccolo pointing out that array-like output is allowed.

Takes the name as separate command line arguments, e.g.:

$ ruby script.rb John Jacob Jingleheimer Schmidt

or

$ ruby -e 'p ARGV[1..-2]' John Jacob Jingleheimer Schmidt

Previous code (outputs a proper string):

puts ARGV[1..-2].join" "
  • @Jordan Good idea - however with $><<ARGV[1..-2].join" " it complains about the " " being unexpected, so I'd have to add parentheses - which would add 1 byte in the end. – Flambino Apr 3 '17 at 7:32
  • Ah, of course. My bad. – Jordan Apr 3 '17 at 14:53
  • The original poster said that the output can be an array, so you can shave some characters off by just changing your code to puts ARGV[1..-2], just so you know. – Piccolo Apr 4 '17 at 5:57
  • @Piccolo Huh? I don't see that anywhere? If true; p ARGV[1..-2] for 13 bytes - just looks nothing like the output in OPs challenge – Flambino Apr 4 '17 at 7:49
  • @Flambino codegolf.stackexchange.com/questions/114927/… – Piccolo Apr 4 '17 at 8:16

Golang, 152 81 bytes

import ."strings"
func f(x string)[]string{var k=Fields(x);return k[1:len(k)-1];}

It takes input as "Samantha Vee Hills" (with double quotes) and return the middle name to the stdout.

Try it Online!

Edit: @Dada, note that the "function as answer is allowed" shorten my code 71 bytes. a big thanks!

  • Welcome on the site. Submitting a function as answer is allowed, so you could shorten your code by doing something like this: Try it online!. Have a look at the Tips for Golfing in Go! – Dada Apr 4 '17 at 8:02
  • thank you @Dada for tips and shorten my code. It was my first code entry. – ersinakyuz Apr 4 '17 at 8:38

Matlab, 81, 79, 78, 55 Bytes

function x=a(s)
s=strsplit(s);x=strjoin(s(2:end-1));end

Takes in an input string, s, is split (by the default delimiter, whitespace char) into a cell array, from which the middle element is accessed. Then the middle elements are concatenated, or an empty string is returned.

Edit: thanks to Luis Mendo for saving 3 bytes!

Edit 2: Better solution from Ankit!

  • I am not a smart man! edited. – Owen Morgan Apr 2 '17 at 16:26
  • You can't use nnz on a cell array, but I did the other two changes :) – Owen Morgan Apr 2 '17 at 16:45
  • Suggested Edit by Ankit, who doesn't have enough rep to comment. (55 bytes): function x=a(s) s=strsplit(s);x=strjoin(s(2:end-1));end – mbomb007 Apr 3 '17 at 21:09

C, 42 bytes

f(char**b){for(;b[2];printf("%s ",*++b));}

The parameter is a NULL terminated array of pointers to char.

See it work here.

The command line arguments may also be used with the same function.

C, 51 bytes

main(a,b)char**b;{for(;b[3];printf("%s ",b++[2]));}

A full program. Input is done through command line arguments.

See it work here.

C, 54 bytes

f(char**b){*strrchr(*b=strchr(*b,32),32)=0;*b+=!!**b;}

The parameter is an in/out parameter.

See it work here.

  • Welcome to PPCG! – Martin Ender Apr 3 '17 at 20:10
  • I'm receiving the following error when compiling with Visual Studio 2012:error C2100: illegal indirection – Johan du Toit Apr 5 '17 at 14:17
  • @JohanduToit VS is not C11 or even C99 conforming. My code is. As practical proof, both gcc and clang compile a valid program. – 2501 Apr 5 '17 at 20:08

Python 2, 42 19 16 Bytes

lambda n:n[1:-1]

Try it online! Thanks to @Kritixi Lithos for saving 23 bytes! Thanks @math_junkie for saving 3 more bytes. For input, put each part of the name as a string within a list like so:

["Samantha", "Vee", "Hills"]

And yes, the OP has approved a list to be a valid input.

Explanation

lambda n:n[1:-1]    # Returns only the middle elements... pretty literal here
  • 1
    print input()[1:-1] is shorter – Cows quack Apr 2 '17 at 14:36
  • Spring slicing sure is tricky – Anthony Pham Apr 2 '17 at 14:38
  • lambda n:n[1:-1] is even shorter – math junkie Apr 2 '17 at 14:43
  • 1
    I may have tried with a wrong input. But when I tried, with Samantha Vee Hills as input in repl.it link that you've shared, this just prints amantha Vee Hill which is definitely not the output required. – Keerthana Prabhakaran Apr 2 '17 at 14:46
  • 2
    Names will always have at least 2 space-separated parts is the first point of the question right. – Keerthana Prabhakaran Apr 2 '17 at 14:47

C++, 91 bytes

#import<list>
#import<string>
void f(std::list<std::string>&n){n.pop_front();n.pop_back();}

Takes input as a reference to a list of strings and modifies the list directly.

Try it online!

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.