We all know that if you google the word "google" it will break the internet.

Your task is to create a function that accepts one string and returns its length, in the fewest possible Unicode characters.

However, if the given string is google (lowercase), it will cause an error.

For example, g('bing') will return 4 but g('google') will cause an error.

Please provide an example of usage, and the error if possible.

• @Geobits That is simply a test to see if I will google Google, which I will not. :D – rybo111 Sep 28 '15 at 16:33
• Does the function need to be case sensitive? Should it throw given 'gOOgle'? – AXMIM Sep 30 '15 at 22:07
• When I type google into google (the search bar on chrome), a message came up asking if I wanted to go to google. (Now that it is a tld, this makes sense i.e. com.google works). I clicked it and got a dns lookup error. Internet:broken! – Craig Oct 1 '15 at 4:18
• I'm voting to reopen this. I have seen no questions about what constitutes an error for this challenge and it already has 154 answers so I don't think it's fair to change the spec. This may not be an example of a good question but it's clear enough. If an answer really comes down to whether or not a certain output is an error it probably just won't get as many upvotes, anyway. – Poke Aug 1 '18 at 19:52

ECMA6,30

g=(s)=>s=="google"?-1:s.length


Since a string length of -1 is an error I think this is a valid answer in Javascript (ECMA6).

I was initially inspired by the python trick of causing a division by zero mentioned near the top. However this does not work in Javascript because you can divide by zero and get "Infinity" without throwing an error so I looked into other options.

This works in Chrome you can copy this into the dev console and then run it by calling g("some string here"). I assume any other browser that has partial support for ECMA6 should be able to run it.

# C++, 81

int l(char *s){int b=0,i=0;do{b=s[i]^"google"[i]?1:b;}while(s[i++]);return--i/b;}


Divides by 0 on "google". This is my first C++ golf, so any tips would be welcome.

^ is used like !=. b is equal to 1 when the string is not "google", 0 if it is. So i/s will result in i/0.

## TSQL 2012, 87

CREATE FUNCTION g(@p CHAR(9))RETURNS INT AS BEGIN RETURN IIF(@p='google',@p,LEN(@p))END


How to use :
SELECT dbo.g('gogle')
-- return 5

--return Conversion failed when converting the varchar value 'google ' to data type int.

# ><>, 108 bytes

i:"g"=1-?v\]
i:"o"=1-?v\
i:"o"=1-?v\
i:"g"=1-?v\
i:"l"=1-?v\
i:"e"=1-?v\
i:01-=1-?v\
>i:0)?v~l n;
^     <  <


Try it here

## AHK, 75 bytes

Inputbox,s
MsgBox % a(s)
a(b)
{
return StrLen(b)
throw b
}


there is no proper stdin and stdout support in ahk so im using inputbox and msgbox, the concept is the same tho.

## Go: 92, 63, 59 bytes with panic instead of error

func g(s string)int{if s=="google"{panic(0)};return len(s)}

• Welcome to PPCG! This is a codegolf challenge, so you should remove all spaces and newlines to get a much lower byte count. You won't get many upvotes, if you post such an ungolfed version. – Jakube Sep 30 '15 at 10:09
• thanks for the welcome. But, Go doesn't allow one to stray too far away from the standard formatting, I'll update the answer in a minute – user45561 Oct 1 '15 at 14:07
• using panic() instead of returning error saves some bytes: func g(s string)int{if s=="google"{panic("")};return len(s)} (60 bytes) – Fabian Schmengler Oct 3 '15 at 16:59

# ><>, 47 bytes

i:0(?\
?\ln;>~l6=
"\ "elgoog
!\{=?!\l ?
=< ;n6<


Here's a line-by-line breakdown:

i:0(?\


A standard ><> input loop, pushes the input string followed by -1.

?\ln;>~l6=


Starts at >. Discards the -1, checks the length is equal to 6. If it is, move to next line, otherwise gets the length, prints, and exits.

"\ "elgoog


Starts at \. Pushes 'google' in reverse. If the input string was google, stack is now googleelgoog

!\{=?!\l ?


Starts at the first \. Rolls the stack one to the left. If top two elements aren't equal, moves to next line. Otherwise, if the stack is length is zero, the strings are equal, so also step to next line.

=< ;n6<


Starts on the 1st < if the string was 'google'. This is only reached when the stack is empty, so attempting to pop any number of values will cause an error - in this case, = is used. If the string wasn't 'google', outputs 6 and exits.

# J, 18

   #^@.('google'-:])


Usage:

   #^@.('google'-:]) 'googl'
5
#^@.('google'-:]) 'google'
|domain error


Explanation

Count (#) if y does not match (-:]) the string 'google', but if it does match, compute e to the power of the string 'google', which is an error.

# OCaml 42 bytes

This does exactly what is asked1: it returns a function which returns the length of its (string) argument, except when the argument is "google", in which case it fails with:

Exception: Division_by_zero.

function"google"->0/0|s->String.length s;;


It doesn’t provide any way to actually call that function, though. In order to do that, you could either write:

(function"google"->0/0|s->String.length s)"some string";;


or you could, you know, give it a name.

let f=function"google"->0/0|s->String.length s;;
f"bing";;


Unpacked, this would give:

(* let f be function with one argument. *)
let f = function
(* If the argument matches exactly "google", return 0/0 *)
| "google" -> 0 / 0
(* If no previous cases were a match, give your argument the name 'string'. *)
(* and return its length. *)
| string   -> String.length string
;;
(* Call f with "bing" as it’s argument. *)
f "bing";;


The type of 0 / 0 is int, so the function is correctly typed as string -> int.

1. Well, I must admit I have not checked these pesky Unicode details.

# Perl, 494639 31 bytes

sub g{sub g{$_=pop;y///c/!/^google$/}}


Call with g(string), print with print g(string).

How it works

The ternary operator only evaluates the expression if the condition is met. So when the input isn't google, it simply returns the original string and passes it on to length. However, is the input is google, it tries to divide by zero and causes this error:

Illegal division by zero at filename.pl line 1.


And as we all know, dividing by zero will break the internet (and the rest of reality).

Changes

• Saved 3 bytes by changing return to print and removing unneeded parentheses.
• Saved 6 bytes thanks to @manatwork, and saved an additional 1 byte by re-arranging my code.
• Saved 8 bytes and fixed an error thanks to @Grimy.
• Wouldn't save more by returning, but implicitly, without using the return keyword? sub g{length($_[0]=~"google"?1/0:$_[0])} – manatwork Sep 30 '15 at 18:13
• @manatwork I'll add that in. Thanks! – ASCIIThenANSI Sep 30 '15 at 19:04
• This will incorrectly raise an error for any string that contains “google” (e.g. “ungoogleable”). A shorter and more correct version would be: sub g{$_=pop;y///c/!/^google$/} – Grimy Oct 5 '15 at 11:32
• @Grimy Thanks for pointing that out, I've added that in. – ASCIIThenANSI Oct 9 '15 at 20:21

# Zsh and bc, 29 bytes

[ "$1" = google ];bc<<<$#1/$?  Sample output: $ zsh not_google.sh oogle
5
$zsh not_google.sh google Runtime error (func=(main), adr=5): Divide by zero  ## Explanation: The first command exits true (zero) when the argument equals "google" and false (one) otherwise. That exit code is stored in $? until another command completes, allowing us to divide by that number.

We then run bc (with input via herestring) to compute the length of the argument divided by that exit code. This is either length ÷ 1 (the length) or length ÷ 0 (an error).

An un-golfed version:

if [ "$1" = google ]; then divisor=0 else divisor=1 fi length="${#1}"
echo "$length /$divisor" |bc


# Bash and bc, 31 bytes

This uses the same logic, but bash can't handle $#1 without braces: [ "$1" = google ];bc<<<${#1}/$?


# Zsh and bc, 26 bytes (also errors on empty string)

This version also has an error when given an empty string, so I assume it doesn't count. It has the exact same output as the previous version (except when given an empty string or no argument).

bc<<<$#1/(0!=${#1#google})


## Un-golfed version of 26 byte answer:

length="${#1}" # the length of the first argument unprefix_google="${1#google}"  # google → "", googler → r, goog → goog, "" → ""
length_unprefix_google="${#unprefix_google}" if [ 0 != "$length_unprefix_google" ]; then
divisor=1                # $unprefix_google is an empty string else divisor=0 #$unprefix_google is not empty
fi

echo "$length /$divisor" |bc


## Java, 96 Bytes

This should work, but IDK for sure since I cant assess a computer at the moment:

Golfed:

 int g(String s){if(s.equals("google"))throw new
IllegalArgumentException();return s.length();}


Ungolfed:

int g(String s){
return s.length(); }


I realize I could proably shorten this, let me know in the comments.

• Actually, I could just divide the string google by a number and get some type-mistmatch error – Ashwin Gupta Dec 4 '15 at 17:45
• Wouldn't a type mismatch be checked at compile time, not run time, because of type erasure? – cat Mar 25 '16 at 15:49
• @tac probably. Could be a workaround through try catch – Ashwin Gupta Mar 25 '16 at 17:16

# Go, 11010293 92 bytes

It makes sense to use a language developed by Google employees to Google Google!

note that this is actually a valid, compilable program, unlike the other go answer.

will take input forever until "google" is input:

package main
import."fmt"
func main(){a:=""
Scan(&a)
Print(len(a))}

example i/o:

bing
4
oogle
5
panic: 0

goroutine 1 [running]:
runtime.panic(0x480e60, 0xc21000a190)
/usr/lib/go/src/pkg/runtime/panic.c:266 +0xb6
main.main()
exit status 2


ungolfed:

package main

import . "fmt"

func main() {
a := ""
Scan(&a)
panic(0)
}
Print(len(a))
}

apparently i had forgotten that var a string is just "" aka empty string. sigh.

# Milky Way 1.0.0, 18 bytes

This language was created after the challenge was posted.

'?{"google"b~z~y!}


### Explanation

'                   # read input from command line
?{         ~ ~  }  # if-else statement
b        # == on top two stack items (input and "google")
z      # non-existent opcode raises an exception
y    # push the length of the TOS to the stack
!   # output the TOS


# Milky Way (current version), 18 bytes

'?{"google"b_z_y!}


### Usage

The code is called via the command line as follows:

./mw <path-to-code> -i <input>


# Lua, 42 bytes

function g(s)return #(s~='google'and s)end


This creates a function g that takes an argument s and (assuming it is a string) returns the length (#) of the result of the evaluation s~='google'and s, which equates to s if s is not 'google', or false if it is. Since there is no length of false, if s is google, this will error, else, it will return the length. Simple and effective.

I know there are other Lua answers, and that I could shorten this by using io.read(), but I'm going to disregard both of those for the same reason: they don't actually use functions, like the question specifically calls for.

If I'm wrong in that it doesn't need to be a function, we can cut this to 32 bytes by doing:

s=io.read()g=#(s~='google'and s)


# jq, 39 characters

def g(s):s|length/({"google":0}[s]//1);


Sample run:

bash-4.3$bin/jq -n 'def g(s):s|length/({"google":0}[s]//1); g("google")' jq: error (at <unknown>): number (6) and number (0) cannot be divided because the divisor is zero bash-4.3$ bin/jq -n 'def g(s):s|length/({"google":0}[s]//1); g("yahoo")'
5


On-line test:

And it even works with foreign languages ...

Note: Mathcad displays errors by showing the expression in red; clicking on the expression shows the error message.

# Rust, 41 chars

rust solution, provided by a friend who does have a rep of 10 to post (and asked me to post it on his behalf).

|x:str|{if x=="google"{panic!();}x.len()}


# TI-83 Basic, 21 bytes

Simple solution. (Lowercase tokens are two bytes each).

length(Ans)/(Ans≠"google


Alternate solution (22 bytes):

If Ans="google
.
length(Ans


Alternate solution (23 bytes):

length(Ans)+0/(Ans≠"google

• This is exactly what I posted in a comment siz months ago. Additionally, you aren't allowed to take input through Ans anymore; there's a meta post about it. – lirtosiast Mar 29 '16 at 21:45

# Molecule (v5.6+), 16 bytes

I_"google"=?p¿#


Explanation:

I_"google"=?p¿#
I_              duplicate
?p¿  if true, do a primality test on "google"
# get length


This way the program will error and shutdown if it does a primality test on a string.

## Pyth, 12 bytes

/lznz"google


• This isn't really working for me here. If I enter "Hello" It should return 5, but it returns {} 2.584962500721156, and if I enter "google" it doesn't cause an error. – DJMcMayhem Apr 26 '16 at 20:39
• @DrGreenEggsandHamDJ Try it here – macleos Apr 26 '16 at 20:48
• The spec asks for a function. This is a full program. – Dennis Nov 21 '16 at 0:21

# Python, 47 bytes

a=input()

• It should print the length of the string if the string is not "google", not the string itself. replacing else a with else len(a) will do the trick. – cat Nov 21 '15 at 22:21

# Ruby, 26 bytes

Not shorter than the existing ones, but an alternative solution.

->x{(x=='google'||x).size}


If given google, it tries to do true.size which results in an error:

NoMethodError: undefined method size' for true:TrueClass


## Clojure, 35 33 bytes

#(/(count %)(if(= %"google")0 1))


(def g #(/(count %)(if(= %"google")0 1)))

ArithmeticException Divide by zero  clojure.lang.Numbers.divide

(g "bing")

4


Unfortunately, 0 is true is Clojure, and there aren't any simple ways of casting a bool to an int anyways, so I had to spend some bytes on a ternary. Still ended up being shorter than my first attempt.

V1: #(if(= % "google")(/ 1 0)(count %)))

# Edited processing JS: 68 bytes

var a =function(i){if(i==="google"){throw"a";}else{print(i.length);}};


Used a edited version of processing. When run here you can see it works. If you input google then the error buddy pops up without any message. This is my first golf!

Edited version of processing (didn't cheat by making my own version) https://github.com/Khan/processing-js

• Who edited it? Because you aren't allowed to edit a language to improve your score. – user63571 Jan 24 '17 at 23:06
• I did not edit it. The khanacademy team edited it. github.com/Khan/processing-js It is its own fork. – Christopher Jan 24 '17 at 23:17
• That's ok then. Just checking ;) – user63571 Jan 24 '17 at 23:37
• Yeah otherwise my language would be called g. It would just have functions called with one byte :P – Christopher Jan 24 '17 at 23:38
• Smart idea! Why don't you make it? – user63571 Jan 24 '17 at 23:54

# Ruby, 19+1 = 20 bytes

Uses the -n flag. Because -n includes the trailing newline for any line of input, it must be piped in from a file w/o the trailing newline or it will not give the error and will instead return 7.

p +~/(?<!^google)$/  Version that requires a trailing newline in the input, so you can type in directly from STDIN, for 20+1=21 bytes p +~/(?<!^google)\n/  Alternate version that works with or without trailing newlines, for 23+1=24 bytes. +(! ~/^google$/&&p~/$/)  All versions return the following error: undefined method +@' for nil:NilClass (NoMethodError)  # tcl, 46 proc x s {if \$s=="google" !;string length $s}  demo # 05AB1E, 8 bytes (non-competing) g¹“Š¹“Ê÷  Uses the CP-1252 encoding. Try it online! Explanation:  # Implicit input g # Take length ¹ # Get first input “Š¹“Ê # != compressed form of "google" ÷ # Integer division (Zero Division Error if invalid)  • There's no error in 05AB1E. It just doesn't push a result. – Erik the Outgolfer Apr 6 '17 at 12:01 ## GNU sed, 137 bytes Adding to the diversity of languages used here, I present a sed answer. There are no integer types or arithmetic operations in sed, so I wrote an increment method to get a string's length (111 bytes). /^google$/{:;s:a*:&&a:;t}
s:^:0,:
:i
s:^9*,:0&:
s:.9*,:/&:;h
s:[0-9]*/::
y:0123456789:1234567890:
x;s:/.*::
G;s:\n::
s:,.:,:
/,./ti
s:,::


The first line of code checks if the input string is google, and if so it continuously increases the pattern space until a memory allocation error is raised. Try it online!

Tests: from a virtual Linux OS I setup with low memory

test@test:~$sed -f google_error.sed <<< "yahoo" 5 test@test:~$ echo $? 0 test@test:~$ sed -f google_error.sed <<< "google"
sed: couldn't re-allocate memory
test@test:~$echo$?
4


# Mathematica, 33 bytes

#=="google"&&1/0||StringLength@#&


TFW Length doesn't work on strings. >.>

## protected by mbomb007Sep 30 '15 at 18:27

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).