g | x | w | all
Bytes Lang Time Link
475Vyxal S230726T121442Zlyxal
075Nibbles230726T121312Zxigoi
005Thunno 2 Ṡ230726T114027ZThe Thon
168Excel170524T133811ZEngineer
491PHP171207T231213ZTitus
006Vim170530T201621ZBlackCap
017Aceto170529T153258ZL3viatha
059PHP170524T065330ZM.E
035PowerShell170529T084402Zcolsw
nanPerl 18+1=19 bytes170526T060726Zuser1775
056Carrot170527T180304Zuser4180
016Retina170524T021233Zuser6198
00705AB1E170524T065917ZAdnan
008V / vim170524T173151ZKevin
010Vim170524T162634ZDJMcMayh
051Python 3170524T013619Zhyper-ne
062Java170524T015955Zhyper-ne
014Japt170524T143603ZArjun
077SNOBOL4170525T001718ZJerry Co
nanRuby170524T020248ZValue In
090R170524T211922ZBLT
052Python 3170524T204937ZAAM111
009Jelly170524T015704ZATaco
040Mathematica170524T020211Zuser6198
038jq170524T133134Zmanatwor
065Scala170524T142709ZJacob
045C170524T072552Zsigvaldm
037MATLAB/Octave170524T073950ZTom Carp
026Bash170524T113405ZMax Mikh
027><>170524T112517ZTeal pel
007Jelly170524T103029ZLeo
018Awk170524T095832Zmanatwor
045PHP170524T082451ZJör
072C#170524T081125ZTheLetha
068C170524T081024Zsigvaldm
023Gema170524T091627Zmanatwor
010MATL170524T090452ZLuis Men
011Pyth170524T084934ZJim
nansed170524T083348ZAaron
039Python 2170524T075434Zxnor
022Ruby170524T065801ZG B
045Mathematica170524T063654ZGreg Mar
00905AB1E170524T062943ZEmigna
034JavaScript ES6170524T061610Zgyre
008Jelly170524T014449Zhyper-ne
044JS ES6170524T013758Zuser5882

Vyxal S, 38 bitsv1, 4.75 bytes

\,+⌈ǔ

Try it Online!

I do not have a comma for a middle name. Ports Thunno 2 but with a range coder.

\,+⌈ǔ­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁤​‎‏​⁢⁠⁡‌­
\,+    # ‎⁡Append a comma
   ⌈   # ‎⁢Split on spaces
    ǔ  # ‎⁣Rotate right once
# ‎⁤The S flag joins on spaces
💎

Created with the help of Luminespire.

Nibbles, 7.5 bytes

*" "::`(\%$~","\

Attempt This Online!

Thunno 2 , 5 bytes

',+OṾ

Try it online!

Explanation

',+OṾ  '# Implicit input
',+    '# Append a ","
   O    # Split on spaces
    Ṿ   # Rotate right
        # Join by spaces
        # Implicit output

Excel, 174 170 168 bytes

Saved 2 bytes thanks to Wernisch

=MID(A1,FIND("^",SUBSTITUTE(A1," ","^",LEN(A1)-LEN(SUBSTITUTE(A1," ",""))))+1,LEN(A1))&", "&LEFT(A1,FIND("^",SUBSTITUTE(A1," ","^",LEN(A1)-LEN(SUBSTITUTE(A1," ","")))))

This is not fancy or clever. It's a fairly basic method. It feels like there should be a shorter way with array formulas but I can't find one that works.

PHP, 49+1 bytes

<?=preg_replace("#^(.*) (\w+)$#","$2, $1",$argn);

Run as pipe with -nF.

Vim, 6 keystrokes

i<C-p>, <End><C-w>

Leaves a trailing space character, which is allowed by the rules

Explanation:
i      Enter insert mode
<C-p>  Autocomplete with last word
,      Write ", "
<End>  Move the cursor to the end of the line
<C-w>  Delete the word behind the cursor

Aceto, 21 17 bytes

,p p
'@'p
pQ$d
r-

I'm sure we can fit this into a 4x4, but I just couldn't do it..

Reads a value, splits it on whitespace, "unqueues" it (a b c -> c a b), prints the first element, prints a comma, sets a catchmark.

Prints a space and the next element (i.e. the first given name). Duplicate the top stack element (a zero if we're done, otherwise the next given name). If that value is truthy (i.e. not 0), jump to the catch mark.

PHP, 62 59 bytes

-3 bytes, thanks Jörg

$a=explode(' ',$argn);echo array_pop($a).', '.join(' ',$a);

Try it online!

Old solution, 63 Bytes

Doesn't work if the person has 3 repeating names.

<?=($a=strrchr($argv[1]," ")).", ".str_replace($a,'',$argv[1]);

Try it online

PowerShell, 35 Bytes

simple regex solution, not too interesting:

"$args"-replace'(.+) (.+)','$2, $1'

Perl 18+1=19 bytes

perl -pe '/\S+$/;$_="$&, $`"'

+1 for -p

Carrot, 56 bytes

#^//\w+$|^.+(?= )/gS";"^ ^*1//;.+(?=;)/S0-1//^\w+| .+$/g

Try it online!

Explanation

Carrot has several global variables, one for each type: string, float and array. The program starts in string-mode, where all the operators will affect the global string variable. And I call these variables the "stack".

Example input is John Fitzgerald Kennedy.

#^                       Set stack-string to the value of the input string
/                        Operator, get matches of this regex on the stack-string and store the matches in stack-array
 /\w+$|^.+(?= )/g        The last name or the first names
S";"                     Convert to string-mode by joining on ";"
                         stack-string = "John Fitzgerald;Kennedy"
^ ^                      Append a space to the stack-string
*1                       Append one copy of the stack-string to itself
                         stack-string = "John Fitzgerald;Kennedy John Fitzgerald;Kennedy "
/                        The match operator
 /;.+(?=;)/              Anything bounded by ";"s except for the last ";"
S0                       Since we are guaranteed to get one match, we can join with any literal, it does not matter. Here we are joining using a 0.
-1                       Remove the first character in the stack-string (the first ";")
                         stack-string = "Kennedy John Fitzgerald"
/                        The match operator
 /^\w+| .+$/g            The first word or the last ones
                         stack-array = ["Kennedy", " John Fitzgerald"]

Luckily for us, the interpreter is bad and displays the result as just Kennedy, John Fitzgerald.

Retina, 19 17 16 bytes

Edit: Thanks to Riker for saving 3 bytes

(.+) (.+)
$2, $1

Try it online!

05AB1E, 7 bytes

Code:

',ì#Áðý

Uses the 05AB1E encoding. Try it online!

Explanation:

',ì         # Prepend the input to ","
   #        # Split on spaces
    Á       # Rotate every element one position to the right (wrapping)
     ðý     # Join the array by spaces

V / vim, 9 8 bytes

$bD0Pa, 

Try it online!

Saved one Byte thanks to

Note there is a trailing space character. Leaves a trailing space, which is allowed per the rules.

Explanation:

$       " move the cursor to the end of the line
 b      " move the cursor to the beginning of the current word
  D     " delete to the end of the line
   0    " move the cursor to the start of the line
    P   " paste in front of the cursor.
     a  " append (enter insert mode with the cursor one character forward)
      , " Literal text, ", "

Vim, 10 bytes/keystrokes

v$F dA, <esc>p

Try it online!

Python 3, 52 51 bytes:

k=input().split()
print(k[-1]+',',' '.join(k[:-1]))

-1 byte thanks to ovs

Java, 110 62 bytes

String d(String s){return s.replaceAll("(.+) (.+)","$2, $1");}

Non-static method.

-48 bytes thanks to Kevin Cruijssen

Japt, 14 bytes

U+', q'  é q' 

A port of @programmer5000's JavaScript answer.

Try it online!

SNOBOL4, 77 bytes

begin
 input arb . f span(&lcase &ucase) . l rpos(0)
 output = l ', ' f
end

This is a pretty straightforward case of pattern matching.

  1. Read a line of input, then match it against:
  2. arbitrary characters (which we'll assign to f), followed by
  3. a span of upper- and lower-case letters (which we'll assign to l) which
  4. matches to the end of the input (rpos(0)).

Having matched those, we write out l, comma and space, f.

Ruby, 26+1 = 27 bytes

Uses the -p flag for +1 byte. Probably can be redone shorter in Retina. And it was!

-1 byte from Kevin Cruijssen.

gsub /(.+) (.+)/,'\2, \1'

Try it online!

R, 90 bytes

function(s){b=el(strsplit(s,' '))
l=length(b)
paste0(b[l],', ',paste(b[-l],collapse=' '))}

Anonymous function. Takes the string, splits it, outputs the last name, a comma, and the rest of the names from the beginning. Would love to see something better, I'm not too good at manipulating strings in R.

Python 3, 52 bytes

lambda s:s.split()[-1]+", "+" ".join(s.split()[:-1])

Very simple, could use golfing help. Just puts the last word at the front and joins them with ", ".

Testcase:

>>> f=lambda s:s.split()[-1]+", "+" ".join(s.split()[:-1])
>>> f("Monty Python")
'Python, Monty'
>>> f("Albus Percival Wulfric Brian Dumbledore")
'Dumbledore, Albus Percival Wulfric Brian'

Jelly, 9 bytes

ḲµṪ;⁾, ;K

Explained, ish:

ḲµṪ;⁾, ;K
Ḳ           # Split the input by spaces
 µ          # Separate the link into two chains. Essentially calls the right half with the split string monadically.
  Ṫ         # The last element, (The last name), modifying the array.
   ;        # Concatenated with...
    ⁾,      # The string literal; ", "
       ;    # Concatenated with...
        K   # The rest of the array, joined at spaces.

Try it online!

Try on all test cases.

Mathematica, 52 40 bytes

StringReplace[x__~~" "~~y__:>y<>", "<>x]

jq, 39 38 characters

(35 34 characters code + 4 characters command line options)

./" "|last+", "+(.[:-1]|join(" "))

Sample run:

bash-4.4$ jq -Rr './" "|last+", "+(.[:-1]|join(" "))' <<< 'John Fitzgerald Kennedy'
Kennedy, John Fitzgerald

Try in jq‣play

jq, 43 characters

(39 characters code + 4 characters command line options)

sub("(?<f>.+) (?<l>.+)";"\(.l), \(.f)")

Just a curiosity: jq only captures named groups, which helps readability, but nothing else.

Sample run:

bash-4.4$ jq -Rr 'sub("(?<f>.+) (?<l>.+)";"\(.l), \(.f)")' <<< 'John Fitzgerald Kennedy'
Kennedy, John Fitzgerald

Try in jq‣play

Scala, 65 bytes

(s:String)=>{val n=s.split(' ');n.last+", "+n.init.mkString(" ")}

C, 45 bytes

EDIT: I just now noticed the requirement for the input possibly having more than two words. I'll leave it as-is with a note that this only works for two words.

EDIT: removed \n. Add 2 bytes if you consider it necessary.

main(a,b)int**b;{printf("%s, %s",b[2],b[1]);}

Compiles with gcc name.c, GCC 6.3.1. Ignore warnings. Usage:

$./a.out Albert Einstein
Einstein, Albert

Abuse of language:

Thanks to @Khaled.K for the tips on using main(a,b)int**b; rather than main(int a, int **b).

MATLAB/Octave, 37 bytes

@(a)regexprep(a,'(.+) (.+)','$2, $1')

Try it online!

Based on @ngenisis' Retina answer, we can also play the regex game in both Octave and MATLAB, saving a fair few bytes over my previous answer.


Old Answer:

I'm going to leave this answer here as well considering it is a more unique way of doing it compared to a simple regex.

Octave, 49 47 bytes

@(a)[a((b=find(a==32)(end))+1:end) ', ' a(1:b)]

Old try it online!

An anonymous function to generate the output.

Basically the code first finds the last space in the string using b=find(a==32)(end). Then It takes the end part of the string (after the space) using a(b+1:end), where b is the output of finding the last space. It also takes the start of the string with a(1:b-1), and concatenates both together with a ', ' in between.

I've already saved a few bytes vs the typical find(a==32,1,'last'). Not quite sure there is much more to save.

Bash, 26 bytes

echo ${!#}, ${@:1:$[$#-1]}

Try it online!

><>, 27 bytes

i:0(?v
" ,"~<^r/
=" ":}o!/?

Try it online!

Jelly, 7 bytes

;”,Ḳṙ-K

Try it online!

I don't know Jelly very well, but reading other answers it looked like they didn't use an optimal algorithm... so here it is:

Explanation

;”,Ḳṙ-K
;”,        Append a comma to the end of the string
   Ḳ       Split on spaces
    ṙ-     Rotate the array by -1 (1 time towards the right)
      K    Join with spaces

Awk, 18 characters

{$1=$NF", "$1}NF--

Sample run:

bash-4.4$ awk '{$1=$NF", "$1}NF--' <<< 'John Fitzgerald Kennedy'
Kennedy, John Fitzgerald

Try it online!

PHP, 45 Bytes

<?=preg_filter("#(.*) (.+)#","$2, $1",$argn);

Try it online!

C#, 76 72 bytes

s=>System.Text.RegularExpressions.Regex.Replace(s,"(.+) (.+)","$2, $1");

Saved 4 bytes with the help of @KevinCruijssen

Old version using substrings for 76 bytes:

s=>s.Substring(s.LastIndexOf(' ')+1)+", "+s.Substring(0,s.LastIndexOf(' '));

C, 68 bytes

Hope it's not wrong to add another post but here's a slightly different solution than my previously posted C solution. This one accepts any number of names.

main(a,b)int**b;{for(printf("%s,",b[--a]);--a;printf(" %s",*++b));}

Compile with gcc name.c (GCC 6.3.1) and ignore warnings. Usage:

$./a.out John Fitzgerald Kennedy
Kennedy, John Fitzgerald

Thanks to @Khaled.K for the tips on main(a,b)int**b;

Thanks for the tip on the for loop to @Alkano.

Gema, 23 characters

* =@append{s; *}
\Z=,$s

The only remarkable thing here is how the challenge managed to hit the weakness of the Gema patterns non-greediness.

Sample run:

bash-4.4$ echo -n 'John Fitzgerald Kennedy' | gema '* =@append{s; *};\Z=,$s'
Kennedy, John Fitzgerald

MATL, 10 bytes

44hYb1YSZc

Try it online!

Explanation

44h    % Implicitly input a string. Postpend a comma
       % STACK: 'John Fitzgerald Kennedy,'
Yb     % Split on spaces
       % STACK: {'John', 'Fitzgerald', 'Kennedy,'}
1YS    % Circularly shift 1 step to the right
       % STACK: {'Kennedy,', 'John', 'Fitzgerald'}
Zc     % Join with spaces between. Implicitly display
       % STACK: 'Kennedy, John Fitzgerald'

Pyth, 11 bytes

jd.>c+z\,d1

Explanation:

jd.>c+z\,d1
     +z\,      Append the "," to the input
    c+z\,d     Split the string on " "
  .>c+z\,d1    Rotate the array one element right
jd.>c+z\,d1    Join the array on " "

Test it online!

sed, 19 + 1 for -E = 20 bytes

s/(.*) (.*)/\2, \1/

Must use -r (GNU) or -E (BSD, recent GNUs) to avoid having to escape the grouping parenthesis.

If written on the command-line, must be enclosed in quotes to avoid being parsed as multiple tokens by the shell :

sed -E 's/(.*) (.*)/\2, \1/'

Python 2, 39 bytes

f,l=input().rsplit(' ',1);print l+',',f

Try it online!

Yup, rsplit.

Ruby, 22 bytes

->s{s[/\w+$/]+", #$`"}

Try it online!

Mathematica, 45 bytes

#/.{a__,s=" ",b__}/;{b}~FreeQ~s->{b,",",s,a}&

Saved a few bytes over ngenisis's answer by taking input as a list of characters rather than as a string. Pure function that uses a pattern-replacement rule.

Mathematica, 49 bytes

#~Join~{","," "}~RotateLeft~Last@Position[#," "]&

Another pure function taking a list of characters as input and returning a list of characters. This one appends "," and " " to the input and then rotates the list of characters until the last space is at the end. (Thus the output has a trailing space, unlike the first function above.)

05AB1E, 9 bytes

#`',«.Áðý

Try it online!

Explanation

#           # split input on spaces
 `          # push each name separately to stack
  ',«       # concatenate a comma to the last name
     .Á     # rotate stack right
       ðý   # join stack by spaces

JavaScript (ES6), 34 bytes

s=>s.replace(/(.+) (.+)/,'$2, $1')

Demo:

let f = s=>s.replace(/(.+) (.+)/,'$2, $1')

;[ 'Albert Einstein', 'John Fitzgerald Kennedy', 'Abraham Lincoln' ].forEach(
  s => console.log(`${s} => ${f(s)}`)
)

Jelly, 8 bytes

Ḳ©Ṫ”,⁶®K

Try it online!

JS (ES6), 52 44 bytes

i=>(i=i.split` `,l=i.pop(),l+", "+i.join` `)