[Question]
  [
Write a program that takes 2 strings as input, and returns the longest common prefix. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer with the shortest amount of bytes wins.
```
Test Case 1:
"global" , "glossary"
"glo"
Test Case 2:
"department" , "depart"
"depart"
Test Case 3:
"glove", "dove"
""
```
  
[Answer]
# Python 3, 54 bytes
Thanks Python for having a built-in function for this task! :D
```
import os;print(os.path.commonprefix(input().split()))
```
Takes input as two words separated by a space such as `glossary global`.
[Answer]
## Haskell, 29 bytes
```
(c:x)%(d:y)|c==d=c:x%y;_%_=""
```
Usage:
```
>> "global"%"glossary"
"glo"
```
Recursively defines the binary function `%` by pattern matching. On two strings with equal first letters, takes that first letters, and prepends it to the function of the remainder of the strings. On anything else, gives the empty string.
[Answer]
# Pyth, ~~8~~ 7 bytes
```
e@F._MQ
```
Thanks @isaacg for 1 byte off
Takes input quoted and comma separated, like `"abc", "acc"`. This exits on an error (but leaves stdout empty) when the result is the empty string. If that is unacceptable, add 2 bytes for `#e@F._MQq`
[Test Suite](http://pyth.herokuapp.com/?code=e%40F._MQ&input=%22global%22%2C%22glossary%22&test_suite=1&test_suite_input=%22global%22%2C%22glossary%22%0A%22department%22%2C%22depart%22%0A%22glove%22%2C%22dove%22&debug=0)
### Explanation
```
e@F._MQ        : implicit Q = eval(input)
   ._MQ        : Map the prefix operator onto both inputs
 @F            : Fold the setwise intersection operator over those lists
e              : Take the last such element, the prefixes are always made from shortest
               : to longest, so this always gives the longest matching prefix
```
[Answer]
## C++, ~~101~~ ~~100~~ 99 bytes
```
#include<iostream>
int i;main(){std::string s,t;std::cin>>s>>t;for(;s[i]==t[i];std::cout<<s[i++]);}
```
Reads two strings from `stdin`, prints the character at the current position from one of the strings while the character at the current position is equal to the character at the same position in the other string.
Thanks to [Zereges](https://codegolf.stackexchange.com/users/43365/zereges) for saving one byte.
[Answer]
## Haskell, 38 bytes
```
((map fst.fst.span(uncurry(==))).).zip
```
Usage example: `( ((map fst.fst.span(uncurry(==))).).zip ) "global" "glossary"` -> `"glo"`.
Zip both input string into a list of pairs of characters. Make two lists out of it: the first one with all pairs from the beginning as long as both characters are equal, the second one with all the rests. Drop the second list and extract all characters from the first list. 
[Answer]
# CJam, ~~12~~ ~~11~~ 9 bytes
```
l_q.-{}#<
```
This reads the strings on two separate lines with Unix-style line ending, i.e., `<string>\n<string>\n`.
*Thanks to @MartinBüttner for -1 byte, and to @jimmy23013 for -2 bytes!*
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=l_l.-X%2B%7B%7D%23%3C&input=department%0Adepart).
### How it works
```
l_         e# Read a line (w/o trailing LF) from STDIN and push a copy.
  q        e# Read another line from STDIN (with trailing LF).
           e# The trailing linefeed makes sure that the lines are not equal.
   .-      e# Perform vectorized character subtraction. This yields 0 for equal
           e# characters, a non-zero value for two different characters, and the
           e# characters themselves (truthy) for the tail of the longer string.
     {}#   e# Find the index of the first truthy element.
        <  e# Keep that many characters from the first string.
```
[Answer]
# APL, 13
```
{⊃↓K/⍨=⌿K←↑⍵}
```
This is a function that takes an array of two strings, and returns the prefix:
```
      {⊃↓K/⍨=⌿K←↑⍵}'glossary' 'global'
glo
      {⊃↓K/⍨=⌿K←↑⍵}'department' 'depart'
depart
```
[Answer]
# AppleScript, 215 Bytes
And I tried so hard... ;(
```
set x to(display dialog""default answer"")'s text returned
set a to(display dialog""default answer"")'s text returned
set n to 1
set o to""
repeat while x's item n=a's item n
set o to o&x's item n
set n to n+1
end
o
```
I wanted to see how well AppleScript could pull this off, and *man* is it not built for string comparisons.
[Answer]
# sed, 18
I had something much longer and more complicated in mind, so credit for [this idea goes to @kirbyfan64sos](https://codegolf.stackexchange.com/a/62779/11259).
```
s/(.*).* \1.*/\1/
```
Includes +1 for the `-r` option to sed.
[Answer]
## C#, ~~201~~ 147 bytes
```
using System.Linq;class a{static void Main(string[]a){a[0].Take(a[1].Length).TakeWhile((t,i)=>a[1][i]==t).ToList().ForEach(System.Console.Write);}}
```
I know it isn't terribly competitive. I just wanted to see what it would look like.
EDIT: Thanks Ash Burlakzenko, Berend, and Dennis\_E
[Answer]
# [rs](https://github.com/kirbyfan64/rs), 14 bytes
```
(.*).* \1.*/\1
```
[Live demo and test cases.](http://kirbyfan64.github.io/rs/index.html?script=%28.*%29.*%20%5C1.*%2F%5C1&input=global%20glossary%0Adepartment%20depart%0Aglove%20dove)
This is pretty simple. It just matches the...longest common prefix and removes the rest of the string. If there is no longest common prefix, it just clears everything.
[Answer]
# CJam, 12 8 26
```
r:AAr:B.=0#_W={;;ABe<}{<}?
```
[Try it Online.](http://cjam.aditsu.net/#code=r%3AAAr%3AB.%3D0%23_W%3D%7B%3B%3BABe%3C%7D%7B%3C%7D%3F&input=glowing%20glow)
(Got idea to use .= instead of .- after looking at Dennis's answer.)
With all the edge cases, it became to hard for a CJam beginner like me to keep it short. Hopefully, this at least works for all cases.
[Answer]
## Common Lisp, 39
```
(lambda(a b)(subseq a 0(mismatch a b)))
```
Takes two string arguments, determines the index *i* where they differ, and returns a substring from 0 to *i*.
[Answer]
# Javascript ES6, 52 bytes
```
f=(a,b)=>[...a].filter((e,i)=>e==b[i]?1:b='').join``
```
Usage:
```
>> f("global","glossary")
"glo"
```
[Answer]
## Perl 5, ~~20~~ ~~19~~ 18 bytes
19 bytes, plus 1 for the `-E` flag instead of `-e`:
```
say<>=~/^(.*).* \1/
```
This is copied shamelessly from [Digital Trauma](/u/11259)'s [sed answer](/a/62806). It assumes the input is a couple of words without spaces in them (or before the first) and with one space between them.
---
Update:
[ThisSuitIsBlackNot](/u/31388) suggested using `-pe` as follows, to save a byte (thanks!):
```
($_)=/^(.*).* \1/
```
And then [Luk Storms](/u/42827) suggested using `-nE` as follows to save another byte (thanks!):
```
say/^(.*).* \1/
```
(I'm counting `-E` as one byte instead of the standard `-e`, but `-n` or `-p` as two. My impression is that that's SOP around here.)
[Answer]
# Python 3, 72
31 bytes saved thanks to FryAmTheEggman.
8 saved thanks to DSM.
```
r=''
for x,y in zip(input(),input()):
 if x==y:r+=x
 else:break
print(r)
```
[Answer]
## Python 3, 47
```
def f(w):[print(end=c[c!=d])for c,d in zip(*w)]
```
A function that takes a list `w` of two words, and prints the common prefix before terminating with an error.
Python 3's `print` function lets you prints strings flush against each other with `print(end=c)` (thanks to Sp3000 for saving 3 bytes with this shorter syntax). This repeatedly take two letters from the words, and prints the first of the letters. The indexing `c[c!=d]` gives an out-of-bounds error where `c!=d`, terminating the execution when two unequal letters are encountered.
An explicit for loop is one char longer than the list comprehension:
```
def f(w):
 for c,d in zip(*w):print(end=c[c!=d])
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~11~~ 9 bytes
```
y!=XdYpf)
```
[Try it online!](https://tio.run/##y00syfn/v1LRNiIlsiBN8/9/9ZTUgsSiktzUvBJ1LignNUUdAA "MATL – Try It Online")
*(-2 bytes thanks to Giuseppe)*
```
 y  % implicitly input the two strings, then duplicate the
    %  first one into the stack again
    %  stack: ['department' 'deported' 'department']
 !  % transpose the last string into a column vector
 =  % broadcast equality check - gives back a matrix comparing
    %  every letter in first input with the letters in the second
 Xd % diagonal of the matrix - comparison result of each letter with
    %  only corresponding letter in the other string
    %  stack: ['department' [1; 1; 1; 0; 1; 1; 0; 0;]]
 Yp % cumulative product (so only initial sequence of 1s remains
    %  1s, others become 0)
    %  stack: ['department' [1; 1; 1; 0; 0; 0; 0; 0;]]
 f  %  find the indices of the 1s
 )  % index at those elements so we get those letters out
    % (implicit) convert to string and display
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 14 bytes
Uses the same idea as [kirbyfan64sos](https://codegolf.stackexchange.com/a/62779/34718). Unfortunately, despite Martin's claim that eventually Match mode will feature a way to print capturing groups, it hasn't been implemented yet. Otherwise, `(.*).* \1` could be used along with 2 bytes or so for some not-yet-existing configuration string option.
```
(.*).* \1.*
$1
```
Each line would go in its own file, with 1 byte added per additional file. Alternatively, run in a single file with the `-s` flag.
[Answer]
# K, 24 bytes
```
{(+/&\=/(&/#:'x)#'x)#*x}
```
Find the minimum of the length of each string. (`(&/#:'x)`). Trim each string to that length (`#'x`). Then compare, smear and sum the resulting sequence:
```
  =/("globaa";"glossa")
1 1 1 0 0 1
  &\=/("globaa";"glossa")
1 1 1 0 0 0
  +/&\=/("globaa";"glossa")
3
```
Finally, take that many characters from the first of the strings provided (`#*x`).
In action:
```
 f: {(+/&\=/(&/#:'x)#'x)#*x};
 f'(("global";"glossary")
    ("department";"depart")
    ("glove";"dove")
    ("aaa";"aaaaa")
    ("identical";"identical")
    ("aca";"aba"))
("glo"
 "depart"
 ()
 "aaa"
 "identical"
 ,"a")
```
[Answer]
## Powershell, 65 bytes
Compare the strings, shrinking the first until it either matches (print and exit) or the string is null and the loop terminates.
```
param($a,$b)while($a){if($b-like"$a*"){$a;exit}$a=$a-replace".$"}
```
[Answer]
# Julia, 62 bytes
```
f(a,b)=(c="";for(i,j)=zip(a,b) i!=j?break:(c*=string(i))end;c)
```
Ungolfed:
```
function f(a::AbstractString, b::AbstractString)
    # Initialize an output string
    c = ""
    # Iterate over the pairs of characters in a and b,
    # truncated to the shorter of the two lengths
    for (i, j) in zip(a, b)
        if i == j
            # If they match, append to the output string
            c *= string(i)
        else
            # Otherwise stop everything!
            break
        end
    end
    return c
end
```
Fixed an issue (at the hefty cost of 14 bytes) thanks to xnor!
[Answer]
## C99, 73 bytes
```
main(int c,char *a[]){for(char *x=a[1],*y=a[2];*x==*y++;putchar(*x++));}
```
Similar to [this answer](https://codegolf.stackexchange.com/a/62967/7464), but shorter and meets spec (takes input from stdin).
[Answer]
## MATLAB, ~~50~~ 40 bytes
Defines a function that accepts 2 strings as input, outputs to command window
```
function t(a,b);a(1:find([diff(char(a,b)) 1],1)-1)
```
This solution will work for any string, outputs 
```
ans =
   Empty string: 1-by-0
```
if no match is given.
Can be golfed by using a script instead of a function (using local variables a, b) (-16 bytes).
so getting 34 Bytes
```
a(1:find([diff(char(a,b)) 1],1)-1)
```
The function style (which seems to be the accepted style), yields 
```
@(a,b)a(1:find([diff(char(a,b)) 1],1)-1)
```
(Thanks @Stewie Griffin)
[Answer]
# [Perl 6](http://perl6.org), 28 bytes
I came up with two that take their values from STDIN which are based on the Perl 5 answer.
```
lines~~/(.*).*' '$0/;say ~$0
```
```
lines~~/:s(.*).* $0/;say ~$0
```
The first requires exactly one space between the inputs, while the other requires at least one whitespace character between the inputs.
---
That is quite a bit shorter than the first thing I tried which takes the values from the command line.
```
say [~] map ->($a,$b){$a eq$b&&$a||last},[Z] @*ARGS».comb # 58 bytes
```
or even the lambda version of it:
```
{[~] map ->($a,$b){$a eq$b&&$a||last},[Z] @_».comb} # 52 bytes
```
Though this is much easier to adjust so that it accepts any number of input strings, at the cost of only one stroke.
```
{[~] map ->@b {([eq] @b)&&@b[0]||last},[Z] @_».comb} # 53 bytes
#          ┗━┛ ┗━━━━━━━┛  ┗━━━┛
```
```
my &common-prefix = {[~] map ->@b {([eq] @b)&&@b[0]||last},[Z] @_».comb}
say common-prefix <department depart>; # "depart"
say common-prefix; # ""
say common-prefix <department depart depot deprecated dependant>; # "dep"
# This code does not work directly with a single argument, so you have
# to give it an itemized List or Array, containing a single element.
say common-prefix $('department',); # "department"
# another option would be to replace `@_` with `(@_,)`
```
[Answer]
# Japt, 27 bytes
**Japt** is a shortened version of **Ja**vaScri**pt**. [Interpreter](https://codegolf.stackexchange.com/a/62685/42545)
```
Um$(X,Y)=>$A&&X==VgY ?X:A=P
```
(The strings go into the Input box like so: `"global" "glossary"`)
This code is exactly equivalent to the following JS:
```
A=10;(U,V)=>U.split``.map((X,Y)=>A&&X==V[Y]?X:A="").join``
```
I have not yet implemented anonymous functions, which is what the `$...$` is for: anything between the dollar signs is left untouched in the switch to JS. After I add functions, this 21-byte code will suffice:
```
UmXY{A&&X==VgY ?X:A=P
```
And after I implement a few more features, it will ideally be 18 bytes:
```
UmXY{AxX=VgY ?X:AP
```
Suggestions welcome!
---
So it turns out that this program is only 15 bytes in modern Japt:
```
¡A©X¥VgY ?X:A=P
```
[Try it online!](https://tio.run/nexus/japt#@39ooeOhlRGHloalRyrYR1g52gb8/6@UnpOflJijpABiFBcnFlUqAQA "Japt – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ø€ËγнÏ
```
[Try it online](https://tio.run/##yy9OTMpM/f//8I5HTWsOd5/bfGHv4f7//9Nz8pMSc7iAVHFxYlElAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWWCy9EF/w/veNS05nD3uc0X9h7u/6/zPzpaKT0nPykxR0kHxCguTiyqVIrViVZKSS1ILCrJTc0rAcpAOGBxoKKyVJAQiAIJlGRkFisAUaJCSWoxSDFcIC@/JCO1CCIMUpmYlGyYkmppkQZUBGQbpaRamKcpxcYCAA).
Or alternatively:
```
ηR.ΔÅ?
```
Might be invalid, since it outputs `-1` instead of an empty string if the strings have no common prefix.
[Try it online](https://tio.run/##yy9OTMpM/f//3PYgvXNTDrfa//@fnpOflJjDBaSKixOLKgE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6P9z24P0zk2JKD7cav@/Vud/dLRSek5@UmKOkg6IUVycWFSpFKsTrZSSWpBYVJKbmlcClIFwwOJARWWpICEQBRIoycgsVgCiRIWS1GKQYrhAXn5JRmoRRBikMjEp2TAl1dIiDagIyDZKSbUwT1OKjQUA).
**Explanation:**
```
ø      # Zip the two (implicit) inputs together, creating pairs
       #  i.e. "abc1de98f" and "abc2de87f"
       #   → ["aa","bb","cc","12","dd","ee","98","87","ff"]
 €Ë    # Check for each if all inner items (the two characters in this case) are the same
       #  → [1,1,1,0,1,1,1,0,0,1]
   γ   # Split it into parts, grouping the same subsequent values together
       #  → [[1,1,1],[0],[1,1],[0,0],[1]]
    н  # Pop and only leave the first item
       #  → [1,1,1]
     Ï # Only leave the characters at the truthy indices in the (implicit second) input
       #  i.e. "abc2de87f" and [1,1,1] → "abc"
       # (after which the result is output implicitly)
η      # Get the prefixes of the first (implicit) input
       #  i.e. "abc1de98f"
       #   → ["a","ab","abc","abc1","abc1d","abc1de","abc1de9","abc1de98","abc1de98f"]
 R     # Reverse this list
       #  → ["abc1de98f","abc1de98","abc1de9","abc1de","abc1d","abc1","abc","ab","a"]
  .Δ   # Then find the first item in this list which is truthy for:
       # (which will result in -1 if none are found)
    Å? #  Check if the second (implicit) input starts with the current prefix
       #   i.e. "abc2de87f" and "abc1d" → 0 (falsey)
       #   i.e. "abc2de87f" and "abc" → 1 (truthy)
       # (after which the result is output implicitly)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~6~~ 4 bytes
```
→¤nḣ
```
[Try it online!](https://tio.run/##yygtzv7//1HbpENL8h7uWPz///@U1ILEopLc1LwSKLO0KBUA "Husk – Try It Online")
-2 bytes from Dominic Van essen.
[Answer]
## Clojure/ClojureScript, 51
```
(defn f[[a & b][c & d]](if(= a c)(str a(f b d))""))
```
Pretty straightforward. Unfortunately the spaces around the parameter destructuring are necessary (that's the `[a & b]` stuff). Not the shortest but I beat some other answers in languages that like to brag about their terseness so I'll post it.
[Answer]
## ed, sed, 19 bytes
## ex, 18 bytes
## vim, 20 bytes
```
s/\(.*\).* \1.*/\1/
```
This also works with ex/vi (heirloom ex 050325), and the trailing slash is not required.
Oddly, this *should* work in vim, but mysteriously fails. It works if I add another unused capture group, something which should not change the semantics of the regex at all:
```
s/\v(.*)(.* \1.*)/\1
```
It fails and gives garbage answers in nvi and the results are downright mysterious:
```
:1
global glossary
:s/\(.*\)\(.*\) \1\(.*\)/\1{\2,\3}/
global{,ry}
```
NOTE: This expects the words on the current [last in the file] line [or every line for the sed script] separated by a space, and containing no space. To operate on every line in ex/vim, add % to the beginning. I don't think I'm the only program here to have constraints like these.
]