| Bytes | Lang | Time | Link |
|---|---|---|---|
| 050 | Red | 241205T081240Z | Galen Iv |
| 041 | JavaScript Node.js | 241205T064925Z | l4m2 |
| 052 | AWK | 241205T063046Z | xrs |
| 005 | Uiua SBCS | 240630T055657Z | chunes |
| 7149 | R | 240616T111935Z | int 21h |
| 005 | Nekomata | 230613T023348Z | alephalp |
| 006 | Thunno 2 | 230611T140056Z | The Thon |
| 010 | 05AB1E | 161212T144422Z | Magic Oc |
| 040 | V vim | 210409T030618Z | Razetime |
| 004 | Vyxal | 210219T102552Z | lyxal |
| 046 | Zsh | 210219T093003Z | pxeger |
| 059 | C | 210202T110456Z | Toby Spe |
| 006 | x8616 machine code | 210202T091328Z | user9915 |
| 004 | Husk | 201023T114906Z | Razetime |
| 006 | Japt h | 201023T105533Z | Shaggy |
| 055 | Kotlin | 200316T080703Z | snail_ |
| 006 | 05AB1E | 200312T175107Z | Kevin Cr |
| 009 | MATL | 180706T130128Z | Sundar R |
| 019 | K oK / K4 | 180706T132308Z | mkst |
| 075 | Rust | 180704T192853Z | null |
| 006 | Jelly | 180704T174851Z | Erik the |
| 062 | C# Visual C# Compiler | 180704T154423Z | Jeppe St |
| 048 | Powershell + Regex | 180703T165204Z | mazzy |
| 012 | Regex | 180703T172211Z | mazzy |
| 077 | Scala | 151105T144201Z | Leonardo |
| 027 | Japt | 151103T230246Z | ETHprodu |
| 076 | Java 8 | 161212T150914Z | Xanderha |
| 145 | Java 7 | 161212T090213Z | Kevin Cr |
| 049 | PHP | 161212T081301Z | jimmy230 |
| 061 | Brainfuck | 161212T073337Z | Mitch Sc |
| 146 | C# | 151105T150934Z | Yytsi |
| 012 | Dyalog APL | 160516T103756Z | Adá |
| 037 | ><> | 160516T113436Z | Sok |
| 067 | Javascript 67 Bytes | 151108T234016Z | Fuzzyzil |
| 028 | Perl 6 | 151108T231231Z | Brad Gil |
| 040 | MATLAB | 151105T124700Z | Jonas |
| 054 | MUMPS | 151110T214855Z | senshin |
| 099 | C++ | 151104T132027Z | sweerpot |
| 047 | Python 3 | 151104T210457Z | xnor |
| 2539 | 𝔼𝕊𝕄𝕚𝕟 | 151104T051821Z | Mama Fun |
| 072 | Python 3 | 151103T184338Z | Morgan T |
| 073 | C99 | 151106T022327Z | Cominter |
| 091 | brainfuck | 151105T200630Z | undergro |
| 090 | Scala | 151104T150748Z | corvus_1 |
| 130 | R | 151105T181413Z | Catherin |
| 044 | Ruby | 151104T162441Z | manatwor |
| 105 | pb | 151105T180305Z | undergro |
| 018 | Perl 5 | 151104T222623Z | msh210 |
| 063 | MATLAB | 151105T104241Z | slvrbld |
| 052 | PHP | 151105T094340Z | insertus |
| 062 | Julia | 151104T043025Z | Alex A. |
| 021 | Minkolang 0.10 | 151105T023618Z | El'e |
| 009 | CJam | 151103T174047Z | Dennis |
| 016 | TeaScript | 151104T043601Z | Downgoat |
| 152 | Java | 151104T223315Z | user4691 |
| 112 | C# | 151104T223841Z | Hand-E-F |
| 065 | Powershell | 151104T221241Z | Jonathan |
| 050 | Python 2 | 151104T005524Z | Zach Gat |
| 034 | Swift | 151104T203709Z | user3369 |
| 147 | C# | 151103T214901Z | Jakothes |
| 019 | ed | 151104T170305Z | Random83 |
| 007 | Pyth | 151103T174628Z | FryAmThe |
| 024 | K | 151104T050507Z | JohnE |
| 051 | Clojure/ClojureScript | 151103T233336Z | MattPutn |
| 215 | AppleScript | 151103T232424Z | Addison |
| 014 | Retina | 151103T223822Z | mbomb007 |
| 052 | Javascript ES6 | 151103T220317Z | Dendrobi |
| 026 | CJam | 151103T173836Z | geokavel |
| 039 | Common Lisp | 151103T215252Z | Joshua T |
| 029 | Haskell | 151103T203240Z | xnor |
| 018 | sed | 151103T192451Z | Digital |
| 054 | Python 3 | 151103T190618Z | Beta Dec |
| 045 | K | 151103T183842Z | kirbyfan |
| 014 | rs | 151103T180149Z | kirbyfan |
| 038 | Haskell | 151103T175451Z | nimi |
| 013 | APL | 151103T174504Z | marinus |
Red, 50 bytes
func[a b][copy/part a find a first difference a b]
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
AWK, 52 bytes
{while((x=substr($1,++i,1))~substr($2,i,1))printf x}
{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
▽\×∊,
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]
- Checks if one string matches the beginning of another one.
- If true, the substring is output.
- 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],"")
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)))
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
ᵃ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ị
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
V (vim), 41 40 bytes
qqhYp$x@qq@qo<esc>j$@qo<esc>:%!awk 'a[$0]++'
jdG
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÷ġṘ
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
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
:
-
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
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)
(-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:
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()
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.
C# (Visual C# Compiler), 62 bytes
(a,b)=>Concat(a.Zip(b,(x,y)=>x==y?x:'$').TakeWhile(x=>x!='$'))
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
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
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);
}
}
}
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.
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>:{=
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)ø⬯)
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.
- If we have the freedom to always supply the shorter string to a, then 8 bytes can be removed.
- If it is allowed to define a and b in the workspace, then another 16 bytes can be removed.
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
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<}{<}?
(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
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