g | x | w | all
Bytes Lang Time Link
050Red241205T081240ZGalen Iv
041JavaScript Node.js241205T064925Zl4m2
052AWK241205T063046Zxrs
005Uiua SBCS240630T055657Zchunes
7149R240616T111935Zint 21h
005Nekomata230613T023348Zalephalp
006Thunno 2230611T140056ZThe Thon
01005AB1E161212T144422ZMagic Oc
040V vim210409T030618ZRazetime
004Vyxal210219T102552Zlyxal
046Zsh210219T093003Zpxeger
059C210202T110456ZToby Spe
006x8616 machine code210202T091328Zuser9915
004Husk201023T114906ZRazetime
006Japt h201023T105533ZShaggy
055Kotlin200316T080703Zsnail_
00605AB1E200312T175107ZKevin Cr
009MATL180706T130128ZSundar R
019K oK / K4180706T132308Zmkst
075Rust180704T192853Znull
006Jelly180704T174851ZErik the
062C# Visual C# Compiler180704T154423ZJeppe St
048Powershell + Regex180703T165204Zmazzy
012Regex180703T172211Zmazzy
077Scala151105T144201ZLeonardo
027Japt151103T230246ZETHprodu
076Java 8161212T150914ZXanderha
145Java 7161212T090213ZKevin Cr
049PHP161212T081301Zjimmy230
061Brainfuck161212T073337ZMitch Sc
146C#151105T150934ZYytsi
012Dyalog APL160516T103756ZAdá
037><>160516T113436ZSok
067Javascript 67 Bytes151108T234016ZFuzzyzil
028Perl 6151108T231231ZBrad Gil
040MATLAB151105T124700ZJonas
054MUMPS151110T214855Zsenshin
099C++151104T132027Zsweerpot
047Python 3151104T210457Zxnor
2539𝔼𝕊𝕄𝕚𝕟151104T051821ZMama Fun
072Python 3151103T184338ZMorgan T
073C99151106T022327ZCominter
091brainfuck151105T200630Zundergro
090Scala151104T150748Zcorvus_1
130R151105T181413ZCatherin
044Ruby151104T162441Zmanatwor
105pb151105T180305Zundergro
018Perl 5151104T222623Zmsh210
063MATLAB151105T104241Zslvrbld
052PHP151105T094340Zinsertus
062Julia151104T043025ZAlex A.
021Minkolang 0.10151105T023618ZEl'e
009CJam151103T174047ZDennis
016TeaScript151104T043601ZDowngoat
152Java151104T223315Zuser4691
112C#151104T223841ZHand-E-F
065Powershell151104T221241ZJonathan
050Python 2151104T005524ZZach Gat
034Swift151104T203709Zuser3369
147C#151103T214901ZJakothes
019ed151104T170305ZRandom83
007Pyth151103T174628ZFryAmThe
024K151104T050507ZJohnE
051Clojure/ClojureScript151103T233336ZMattPutn
215AppleScript151103T232424ZAddison
014Retina151103T223822Zmbomb007
052Javascript ES6151103T220317ZDendrobi
026CJam151103T173836Zgeokavel
039Common Lisp151103T215252ZJoshua T
029Haskell151103T203240Zxnor
018sed151103T192451ZDigital
054Python 3151103T190618ZBeta Dec
045K151103T183842Zkirbyfan
014rs151103T180149Zkirbyfan
038Haskell151103T175451Znimi
013APL151103T174504Zmarinus

Red, 50 bytes

func[a b][copy/part a find a first difference a b]

Try it online!

copy/part a                              ; copy the head of the first string
            find a                       ; that ends at the position
                   first                 ; of the first symbol
                         difference a b  ; in the special difference of the two strings

JavaScript (Node.js), 41 bytes

f=([a,...A],[b,...B])=>[a]==b?a+f(A,B):''

Try it online!

AWK, 52 bytes

{while((x=substr($1,++i,1))~substr($2,i,1))printf x}

Attempt This Online!

{while((x=substr($1,++i,1)) # grab each char from first string
~substr($2,i,1))            # compare to each char of second
printf x}                   # print match

Uiua SBCS, 5 bytes

▽\×∊,

Try it!

Explanation

▽\×∊,­⁡​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌­
   ∊,  # ‎⁡mask of where letters match
 \×    # ‎⁢cumulative product
▽      # ‎⁣keep

R, 71 bytes (the function-only version: 49 bytes)

A recursive approach with regex:

s=scan(,"");`?`=\(a,b)`if`(regexpr(b,a)-1,a?sub(".$","",b),b);s[1]?s[2]

Attempt This Online!

  1. Checks if one string matches the beginning of another one.
  2. If true, the substring is output.
  3. Else remove the last character from the substring, pass to the function and call it again.

Matching substrings:

# R, 80 bytes

s=scan(,"");a=s[1];b=s[2];`+`=\(x)substring(x,1,1:nchar(a));max((+a)[+a==+b],"")

Attempt This Online!

Creates all possible sequential substrings that start from the 1st character for the both strings, subset for those that match and output the longest one.

An attempt to use a built-in abbreviate

# R, 48 bytes

sub(".$","",max(abbreviate(scan(,""),1,F,,,,F)))

Attempt This Online!

Note: unfortunately, this is not a valid answer, as it would fail if the provided strings contain a " ", "\t" or similar. We assume that, if not otherwise specified, an input string might contain at least a space symbol.

Nekomata, 5 bytes

ᵃp=al

Attempt This Online!

ᵃp=al
ᵃp      Non-deterministically choose a prefix of both inputs
  =     Check if the two prefixes are equal
   al   Find the last possible solution, which is the longest

Thunno 2, 6 bytes

Z€ạġhị

Attempt This Online!

Explanation

Z€ạġhị  # Implicit input
Z       # Zip them together
 €      # To each inner pair:
  ạ     #  Check if they're equal
   ġ    # Group consecutive items
    h   # Get the first group
     ị  # Corresponding filter
        # Implicit output

05AB1E, 10 bytes

.ps.p©å®Ï¤

Try it online!

V (vim), 41 40 bytes

qqhYp$x@qq@qo<esc>j$@qo<esc>:%!awk 'a[$0]++'
jdG

Try it online!

No regex.

Takes the strings on two separate lines. The awk command is from here.

Once the matching prefixes are found, we delete everything except the first line.

Vyxal, a, 5 4 bytes

R÷ġṘ

Try it Online!

Explained

R÷ġṘ
R÷   # vectorise reverse over the input (wrapped in an array by the -a flag) and push contents onto the stack
  ġ  # Push the greatest common suffix
   Ṙ # and reverse it to get the prefix

Zsh, 46 bytes

until [[ $1 = ${2%$~s}* ]] {s+=?;}
<<<${2%$~s}

Try it online!

C, 59 bytes

main(int c,char**a){while(*a[1]==*a[2]++)putchar(*a[1]++);}

Input from the command-line arguments.

Note - will overrun after printing the final null character if the input strings are identical.

x86-16 machine code, 6 bytes

00000000  56 A6 74 FD 4E C3                                 V.t.N.

Callable function.

Expects [SI] = address of first string, [DI] = address of second string.

Outputs as: Top of stack = start of memory slice, SI = end of memory slice (like the slice in Python).

Disassembly:

56            PUSH    SI    ; Store original SI onto stack
A6      LOOP: CMPSB         ; Compare [SI++] with [DI++]
74 FD         JZ      LOOP  ; If they're equal, jump to tag 'LOOP'
4E            DEC     SI    ; -- SI
C3            RET           ; Return to caller

Example run

-d 0100
0B4A:0100  56 A6 74 FD 4E C3 00 00-00 00 00 00 00 00 00 00   V.t.N...........
0B4A:0110  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00   ................
0B4A:0120  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00   ................
0B4A:0130  67 6C 6F 62 61 6C 00 00-00 00 00 00 00 00 00 00   global..........
0B4A:0140  67 6C 6F 73 73 61 72 79-00 00 00 00 00 00 00 00   glossary........
0B4A:0150  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00   ................
0B4A:0160  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00   ................
0B4A:0170  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00   ................
-r
AX=0000  BX=0000  CX=0000  DX=0000  SP=FFEA  BP=0000  SI=0130  DI=0140
DS=0B4A  ES=0B4A  SS=0B4A  CS=0B4A  IP=0100   NV UP EI PL NZ NA PO NC
0B4A:0100 56            PUSH    SI
-t

AX=0000  BX=0000  CX=0000  DX=0000  SP=FFE8  BP=0000  SI=0130  DI=0140
DS=0B4A  ES=0B4A  SS=0B4A  CS=0B4A  IP=0101   NV UP EI PL NZ NA PO NC
0B4A:0101 A6            CMPSB
...
-t

AX=0000  BX=0000  CX=0000  DX=0000  SP=FFE8  BP=0000  SI=0133  DI=0144
DS=0B4A  ES=0B4A  SS=0B4A  CS=0B4A  IP=0105   NV UP EI PL NZ NA PE CY
0B4A:0105 C3            RET
-d ss:ffe0
0B4A:FFE0  00 00 00 00 30 01 4A 0B-AE 05 30 01 30 01 00 00   ....0.J...0.0...
0B4A:FFF0  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00   ................
-rsp
SP FFEA
:
-

Husk, 6 4 bytes

→¤nḣ

Try it online!

-2 bytes from Dominic Van essen.

Japt -h, 6 bytes

®å+Ãrf

Try it

Kotlin, 55 bytes

Not-Lame Edition! (no builtin)

{zip(it).takeWhile{(a,b)->a==b}.fold(""){a,(f,_)->a+f}}

{zip(it)                                                 // zip first string with second
        .takeWhile{(a,b)->a==b}                          // take pairs while chars are equal
                               .fold(""){a,(f,_)->a+f}}  // fold into string

Try it online!

05AB1E, 6 bytes

ø€ËγнÏ

Try it online or verify all test cases.

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 or verify all test cases.

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)

MATL, 11 9 bytes

y!=XdYpf)

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

K (oK) / K4, 21 19 bytes

Solution:

(*x)@&&\=/(#,/x)$x:

Try it online!

Explanation:

Pad strings to combined length of the strings, check for equality, find matching indices, take minimum over resulting list, and index into first element of original input at these indices.

(*x)@&&\=/(#,/x)$x: / the solution
                 x: / save input as x
                $   / pad
          (    )    / do together
            ,/x     / flatten (,/) x
           #        / count (returns length)
        =/          / compare, equals (=) over (/)
      &\            / mins, min (&) scan (\)
     &              / indices where true
    @               / index into
(  )                / do this together
 *x                 / first (*) x

Rust, 75 bytes

|a,b|a.chars().zip(b.chars()).take_while(|(a,b)|a==b).map(|v|v.0).collect()

Try it online!

Does unnecessary heap allocation for the result (idiomatic Rust code would return &str here as opposed to String), but it works so whatever. It's not like it matters.

This iterates over string characters as long as characters match and then collects matched characters into a String.

Jelly, 6 bytes

¹Ƥ€f/Ṫ

Try it online!

C# (Visual C# Compiler), 62 bytes

(a,b)=>Concat(a.Zip(b,(x,y)=>x==y?x:'$').TakeWhile(x=>x!='$'))

Try it online!

Zip! This byte count includes only the lambda expression, and some necessary using static directives are not counted.

It is assumed that no word will contain the magical char value $ (otherwise program may fail). Can use \0 instead (but that is longer to type).

Powershell + Regex, 48 bytes

$m=$args-join"`n"-match"(^.*).*`n\1";$Matches[1]

one line input strings only.

Powershell pure, 58 56 bytes

param($a,$b)for($i=0;$a[$i]-eq$b[$i]){$c+=$a[$i++]};"$c"

Test script:

$f = {
param($a,$b)for($i=0;$a[$i]-eq$b[$i]){$c+=$a[$i++]};"$c"
}

"glo" -eq (&$f "global" "glossary")
"depart" -eq (&$f "department"  "depart")
"" -eq (&$f "glove" "dove")

Output:

True
True
True

Regex, 12 bytes

(^.*).*$\n\1

each input string is separate line. https://regex101.com/r/bTf1ud/1

Scala, 85 83 77 bytes

def f(a:String,b:String)=a zip b takeWhile(a=>a._1==a._2) map(_._1) mkString

for example,

f("global" , "glossary")

returns

glo

Japt, 27 bytes

Japt is a shortened version of JavaScript. Interpreter

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!

Java 8, 76 bytes

(a,b)->{String m="";for(int i=0;i<a.length&&a[i]==b[i];)m+=a[i++];return m;}

Lambda that takes 2 char[] arguments. Loops through until the letters stop matching or we match them all, appending them to a blank string as it goes.

Java 7, 145 bytes

class M{public static void main(String[]a){for(char i=0,c;i<a[0].length();){c=a[0].charAt(i);if(c!=a[1].charAt(i++))break;System.out.print(c);}}}

Those pesky program-requirements instead of function..

Ungolfed:

class M{
  public static void main(String[] a){
    for(char i = 0, c; i < a[0].length(); ){
      c = a[0].charAt(i);
      if(c != a[1].charAt(i++)){
        break;
      }
      System.out.print(c);
    }
  }
}

Try it here.

PHP, 49 bytes

<?=substr($t=$argv[1],0,strspn($t^$argv[2],"\0"));

Replace \0 with the actual byte.

Brainfuck, 61 bytes

+
[
  ,[<+> >+<-]
  ++++[>--------<-]
  >
]
<<[<]
<+
[
  ,[>+>-<<-]
  >>[<]
  <[.>]
  <
]

Expects two words separated by a space.

Try it online.

C# 147 146

string l(string a,string b){var s="";for(int i=0;i<Math.Min(a.Length,b.Length);i++){if(a[i]==b[i])s+=a[i];else return a.Substring(0,i);}return s;}

Readable and ungolfed version

    string longestPrefix(string a, string b)
    {
        var s = "";
        for (int i = 0; i < Math.Min(a.Length, b.Length); i++)
        {
            if (a[i] == b[i]) s+=a[i];
            else return a.Substring(0, i);
        }

        return s;
    }

How it works:

It loops until characters on the same index do not match. Every character that matches is added to s string, otherwise return a new string from zero index to current iteration.

Dyalog APL, 12 bytes

{⊥⍨⌽=⌿↑⍵}↑∊

That's two bytes less than the previous APL solution!

The overall function is , which takes n elements (characters) from the flattened () argument, where n is the result of applying the function {⊥⍨⌽=⌿↑⍵} to the argument:

↑⍵ convert list of strings to table (padding with spaces to form rectangle)
=⌿ compare down (columns) giving boolean list
reverse
⊥⍨ count trailing trues*


*Literally it is a mixed-base to base-10 conversion, using the boolean list as both number and base:

⊥⍨0 1 0 1 1 is the same as 0 1 0 1 1⊥⍨0 1 0 1 1 which is 0×(0×1×0×1×1) 1×(1×0×1×1) 0×(0×1×1) 1×(1×1) + 1×(1) which again is two (the number of trailing 1s).

><>, 37 bytes

i:0( ?\
4*=?\$>1+{:8
+[r]\$1
?!;o>:{=

Try it online!

Input is via STDIN, and is expected without quotes, separated by a space. For example, global glossary.

After the input is read, the characters up to and including the space are reversed and pushed back onto the stack. For example, if the input were global glossary, the stack would be glossary labolg. The stack is then rotated to the left one step at a time. If the top two chars are the same, output. Otherwise, end.

Javascript: 67 Bytes

(a,b)=>{for(i=0;i<a.length;i++){if(a[i]!=b[i])return a.slice(0,i)}}

Perl 6, 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 `(@_,)`

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)

MUMPS, 54 bytes

t(a,b) f i=$L(a):-1:0 s p=$E(a,1,i) q:p=$E(b,1,i)
    q p

Typically primitive stuff - it just compares successively-shorter prefixes of the strings until it hits a match.

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 for saving one byte.

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])

𝔼𝕊𝕄𝕚𝕟, 25 chars / 39 bytes

ô⟦ï0]Ă⇀$≔ï1[_]?1:ï1=0)ø⬯)

Try it here (Firefox only).

It barely looks like ES6.

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)

C99, 73 bytes

main(int c,char *a[]){for(char *x=a[1],*y=a[2];*x==*y++;putchar(*x++));}

Similar to this answer, but shorter and meets spec (takes input from stdin).

brainfuck, 91 bytes

+[>>,>++++[<-------->-]<]<<[<<]>+[>>++++[>++++++++<-],]<[<]>>-<[>>[<+>>-<-]+>[<->,]<[<.,]>]

Requires an interpreter that either allows negative positions on the tape or wraps if you < from 0. Also requires , to return 0 every time you use it after input runs out. (In my experience these are both the most common behaviour.) Takes input as two words separated by a space.

This was a lot easier than I expected it to be! Usually I decide to write a brainfuck program and end up devoting quite a bit of time to it, but this one played nice. My first idea ended up working well and being rather short, especially for brainfuck.

This works by getting the entire first word and storing the characters in every second cell, then weaving in the second word (e.g. gglloosbsaalr y). Then, for each pair of characters a and b, it copies a a cell to the left and simultaneously replaces b with b-a. The cell a used to be in becomes NOT (b-a). If that's true, a is printed and the loop continues to the next set of characters. Otherwise, nothing is printed and the loop terminates.

I only used two real golfing tricks in this program. The first was combining two unrelated loops while gathering input. The first word is initially stored with each of its bytes subtracted by 32, so that space becomes 0 and the loop can end. Rather than adding 32 to each of those bytes and then getting the second word, the program does both at the same time. The second trick I used was abuse of , when I know the input is empty. The idiomatic way of setting a cell to 0 is [-]. However, if you know that the program has already read the entire input, most interpreters will let you try to get a byte of input anyway and set the current cell to NUL, or 0. I use this twice in my program, saving 4 bytes.

Ungolfed:

+[>>,>++++[<-------->-]<]          get first word (minus 32 at each byte)

<<[<<]>                            go back to start

+[>>++++[>++++++++<-],]            get second word and add 32 to each byte of
                                   first word

<[<]>>-<                           go back to start and clean up a little bit

[                                  main loop

  >>[<+>>-<-]                        subtract letter from second word from
                                     letter of first word 

  +>[<->,]<                          logical NOT the result

  [<.,]>                             if the result is 1: print the letter
                                     else: the loop dies and execution is
                                     terminated 

]

Scala, 90 bytes

object S extends App{print(args(0)zip args(1)takeWhile{case(a,b)=>a==b}map(_._1)mkString)}

It takes to Strings as arguments and outputs to stdout.

R, 130 bytes

substr(x[1],1,which.max(apply(do.call(rbind,lapply(strsplit(x,''),`length<-`,nchar(x[1]))),2,function(i)!length(unique(i))==1))-1)

Usage:

x <- c('bubblegum','bubbafish')

Ruby, 44 characters

->a,b{i=0;i+=1while a[i]&&a[i]==b[i];a[0,i]}

Sample run:

2.1.5 :001 > ->a,b{i=0;i+=1while a[i]&&a[i]==b[i];a[0,i]}["global , "glossary"]
 => "glo"

2.1.5 :002 > ->a,b{i=0;i+=1while a[i]&&a[i]==b[i];a[0,i]}["department", "depart"]
 => "depart"

2.1.5 :003 > ->a,b{i=0;i+=1while a[i]&&a[i]==b[i];a[0,i]}["glove", "dove"]
 => ""

pb, 105 bytes

^w[B!32]{>}>w[B!0]{t[B]vb[1]<[X]w[B!0]{>}b[T]w[B!1]{>}b[0]^>}v<[X]<t[0]w[T=0]{>t[B]^t[T-B]v}w[B!0]{b[0]>}

Takes two words separated by a single space. (I can save a byte by using a tab instead but that feels like cheating.)

In pb, the area that can be written to is thought of as a 2D space, with (0, 0) in the upper left. Additionally, input is initially kept at Y=-1. This program copies the second word of the input to Y=0 (starting at (0, 0)). Then, each letter is compared to the letter immediately above it until one is found that doesn't match. The rest of the word is erased and the desired output is already on the canvas so it's printed when execution halts.

Ungolfed:

^w[B!32]{>}>       # Go to the first letter of the second word
w[B!0]{            # For each letter in the second word:
    t[B]             # Save the letter to T
    vb[1]            # Put a flag below that letter so it can be found later
    <[X]w[B!0]{>}    # Go to the first empty space on Y=0
    b[T]             # Write the contents of T
    w[B!1]{>}b[0]    # Go back to the flag and erase it
    ^>               # Restart loop from next letter
}

v<[X]<             # Go to (-1, 0)
t[0]               # Set T to 0
w[T=0]{            # While T is 0:
    >t[B]            # Save the next letter of the second word to T
    ^t[T-B]v         # Subtract the equivalent letter of the first word from T

    # If they were the same, T is 0 and the loop continues.
}

w[B!0]{b[0]>}      # Erase the rest of the second word

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's sed answer. 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 suggested using -pe as follows, to save a byte (thanks!):

($_)=/^(.*).* \1/

And then Luk Storms 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.)

MATLAB, 63 bytes

Defines a function that accepts 2 strings as input.

function f(a,b),c=1;try,while a(c)==b(c),c=c+1;end,end,a(1:c-1)

Had to include a try-statement for those cases where a would be a is a longer string than b.

PHP, 52 bytes

Not spectacular but does the job:

$a=$argv;while($a[1][$i]==$a[2][$i])echo$a[1][$i++];

Takes two command line arguments:

php prefix.php department depart

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!

Minkolang 0.10, 21 bytes

(od" "=,)x(0gdo=?.O1)

Expects input as two words, space-separated, like so: department depart. Try it here.

Explanation

(od" "=,)      Loops through input until a space is encountered
x              Dumps extraneous space
(0gdo=   1)    Loops through second word and compares letters
      ?.O      Halts if two letters are not equal, outputs them otherwise

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.

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.

TeaScript, 16 bytes 20

xf»l¦y[i]?1:b=0)

Takes each input separated by a space.

Java, 152 bytes

String a="aa",b="ab";char[]c=a.toCharArray(),d=b.toCharArray();int e=0,f=Math.min(c.length,d.length);for(;e<f&&c[e]==d[e];e++);return new String(c,0,e);

C#, 112 bytes

class P{static void Main(string[]a){try{for(int i=0;a[0][i]==a[1][i];)System.Console.Write(a[0][i++]);}catch{}}}

Newlines and indentation for clarity:

class P{
    static void Main(string[]a){
        try{
            for(int i=0;a[0][i]==a[1][i];)
                System.Console.Write(a[0][i++]);
        }
        catch{}
    }
}

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".$"}

Python 2, 50 bytes

for a,b in zip(*input()):print(1/0if a!=b else a),

Input

The input is taken as two strings:

"global", "glossary"

Output

The output is each character followed by a space; which, hopefully, isn't a problem. However, if it is, I'll edit my answer.

g l o 

Swift, 34 bytes

import UIKit "global".commonPrefixWith("glossary")

But with Swift 2 it is actually more like: "global".commonPrefixWithString("glossary",options:.CaseInsensitiveSearch)

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

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.

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

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

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")

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.

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.

Retina, 14 bytes

Uses the same idea as kirbyfan64sos. 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.

Javascript ES6, 52 bytes

f=(a,b)=>[...a].filter((e,i)=>e==b[i]?1:b='').join``

Usage:

>> f("global","glossary")
"glo"

CJam, 12 8 26

r:AAr:B.=0#_W={;;ABe<}{<}?

Try it Online.

(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.

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.

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.

sed, 18

I had something much longer and more complicated in mind, so credit for this idea goes to @kirbyfan64sos.

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

Includes +1 for the -r option to sed.

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.

K, 45 bytes

{*|(*v)@{&y~'x}.#[&/#:'v;]'v:{#[;x]'1+!#x}'x}

Takes input as a 2-element list.

rs, 14 bytes

(.*).* \1.*/\1

Live demo and test cases.

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.

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.

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