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.

  • 115
    I googled google, and Google found Google on Google. Myth Busted. – Geobits Sep 28 '15 at 16:32
  • 82
    @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
  • 7
    Does the function need to be case sensitive? Should it throw given 'gOOgle'? – AXMIM Sep 30 '15 at 22:07
  • 2
    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
  • 4
    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 at 19:52

144 Answers 144

Python 2, 29

lambda x:len(x)/(x!='google')

Gives a ZeroDivisionError on "google", and the length otherwise. This takes advantage of Python's booleans equaling 0 and 1.

  • 2
    +1. You need to set g to your lambda, or call it anonymously with an input, though. – Zach Gates Sep 28 '15 at 16:44
  • 2
    Just for fun, I tried this technique with JavaScript ES6. It ended up at 25, but returns Infinity for "google" instead of throwing an error... – ETHproductions Sep 28 '15 at 16:55
  • 16
    @ZachGates The consensus on meta is that anonymous functions are allowed unless specifically disallowed. Since the question does seem to imply something like this (but doesn't explicitly disallow it, yet), you should ask the OP about it. – FryAmTheEggman Sep 28 '15 at 16:58
  • 3
    @Kevin you would need a return if you used def – FryAmTheEggman Sep 28 '15 at 20:10
  • 3
    Amusingly, this translated to Pyth does better than my prior best Pyth solution. It is L/lbnb"google, 13 bytes. – isaacg Nov 26 '15 at 6:26

Excel, 23 characters

Paste this into a cell other than A1 and type your search query into A1.

=LEN(A1)/(A1<>"google")

For example:

GoogleGoogle

  • 8
    What's the general consensus on using Excel? – Beta Decay Sep 30 '15 at 17:11
  • 49
    @BetaDecay. Creative, uncommon, seems to work. Won't be applicable to all CG puzzles, but it is here! – kdbanman Sep 30 '15 at 18:03
  • 112
    Managers love it! – lkraider Sep 30 '15 at 18:07
  • 17
    So Efficient, CG Users Will Hate You For It. But Wait. B3 Will Change Your Life Forever! – Sumurai8 Oct 1 '15 at 7:44
  • 7
    What's the specific concensus on using Excel? – GreenAsJade Oct 3 '15 at 23:29

C#, 43 bytes

An improvement over Salah Alami's answer. Recurses to throw a stack overflow exception on providing "google"

int g(string s)=>s!="google"?s.Length:g(s);
  • 2
    Yeah I thought that was a pretty clever way to save some characters to throw an exception. At 4 characters, it might be the smallest way to throw an exception in C#, not sure. – DLeh Oct 1 '15 at 20:05
  • 3
    This is clever! However, recent versions of C# have support for tail recursion so this function will never throw StackOverflowException. In fact it will never return (behaves as while(true){}). – NightElfik Oct 6 '15 at 4:15
  • 1
    @DLeh Tail recursion calls are little bit tricky. You have to run on x64 JIT and without debugger (debugger attached will cause tail recursion to not work for obvious reasons). Here is my program as a proof: imgur.com/ErNl8LJ and little more reading about tail recursion: blogs.msdn.com/b/davbr/archive/2007/06/20/… ;) – NightElfik Oct 10 '15 at 18:52
  • 10
    Haha: g(string)... I'll see myself out... – gregsdennis Nov 17 '15 at 1:45
  • 1
    @DLeh oh wait no I can match your 43 bytes but not beat it. :) int g(string s)=>s!="google"?s.Length:s[9]; – lee Mar 9 at 3:27

Pyth, 14 13 characters

L/lbnb"google

Defines a named function y.

This divides the length by 1 if the string is not google and by 0 otherwise. The idea is not novel, but I came up with it independently.

Try it online.

How it works

L                 Define y(b):
  lb                Compute len(b).
    nb"google       Compute (b != "google").
 /                  Set _ = len(b) / (b != "google").
                  Return _. (implicit)
  • Yeah I'm actually unsure about this, I don't think it's happened before with a string. Normally you could close it with ; but obviously you can't here... – FryAmTheEggman Sep 28 '15 at 17:29
  • You don't need the end quote. – Maltysen Sep 28 '15 at 20:25
  • 44
    "Defines a named function y." But there's no y in your code!? – A.L Sep 29 '15 at 13:03
  • 44
    @A.L That's correct. The built-in L redefines the function y. – Dennis Sep 29 '15 at 14:49
  • 85
    I'm not sure, but I think I hate Pyth. – Mr Lister Sep 30 '15 at 15:36

MATLAB, 63 41 40 38 36 bytes

Thanks to Tom Carpenter for shaving off 1 byte!

Thanks to Stewie Griffin for shaving off 2 bytes!

@(x)nnz(x(+~strcmp('google',x):end))

Unlike the other more elegant solutions, performing a division by zero operation in MATLAB will not give an error, but rather Inf. This solution finds the length of the string by nnz. The string that is produced is in such a way that you index from the beginning of the string to the end, which is essentially a copy of the string. However, what is important is that the beginning of where to access the string is produced by checking whether or not the input is equal to 'google'. If it isn't, this produces a beginning index of 1 and we index into the string normally... as MATLAB starts indexing at 1. Should it be equal, the index produced is 0 and MATLAB will throw an indexing error stating that the index needs to be a positive integer. The extra + is to ensure that the output of the equality check is numerical rather than Boolean/logical. Omitting the + will produce a warning, but because this challenge's specifications doesn't allow for warnings, the + is required... thus completing the code.

Example uses

>> f=@(x)nnz(x(+~strcmp('google',x):end)) %// Declare anonymous function

f = 

    @(x)nnz(x(+~strcmp('google',x):end))

>> f('bing')

ans =

     4

>> f('google')
Subscript indices must either be real positive integers or logicals.

Error in @(x)nnz(x(+~strcmp('google',x):end))

A more fun version, 83 77 76 74 72 bytes

Thanks to Tom Carpenter for shaving off 1 byte!

Thanks to Stewie Griffin for shaving off 2 bytes!

@(x)eval('if strcmp(''google'',x),web([x ''.com/i'']);else nnz(x),end');

The above isn't an official submission, but it's something that's a bit more fun to run. Abusing eval within anonymous functions, what the code does is that it checks to see if the input string is equal to 'google'... and if it is, this will open up MATLAB's built-in web browser and shows Google's 404 error page trying to access the subpage located at i when that doesn't exist. If not, we display the length of the string normally.

Example uses

>> f=@(x)eval('if strcmp(''google'',x),web([x ''.com/i'']);else nnz(x),end'); %// Declare anonymous function
>> f('bing')

ans =

     4

>> f('google')
>> 

The last call using 'google' gives us this screen:

enter image description here

  • 2
    You could save a byte by using strcmp instead of isequal. – Tom Carpenter Sep 29 '15 at 5:47
  • @TomCarpenter - Funny. I actually told myself to use strcmp but ended up using isequal for some reason.... thanks! – rayryeng Sep 29 '15 at 5:53
  • nnz is two bytes shorter than numel. You had my vote a few years ago :-) – Stewie Griffin Oct 17 '17 at 20:13
  • @StewieGriffin Thanks! – rayryeng Oct 20 '17 at 7:52

JavaScript ES6, 34 27 25 characters

f=>f=='google'?Δ:f.length

Throws a ReferenceError on Δ for google.

alert((f=>f=='google'?Δ:f.length)('test'))

  • 10
    You could use a ternary operator to save two bytes. – Konrad Borowski Sep 29 '15 at 13:14
  • 2
    Yay, that's exactly what I just got. If you want to be fancy, use a symbol people never use instead of g to be sure it won't exist as a global variable. Δ makes for a good variable name :) – Jacque Goupil Oct 1 '15 at 17:07
  • 1
    You could use #, it errors in JS afaik – clap Oct 6 '15 at 1:55
  • 5
    Δ Google Illuminati confirmed – DynamiteReed Oct 7 '15 at 1:59
  • 1
    I'm just going to leave this here github.com/Rabrennie/anything.js – sagiksp Mar 9 '17 at 10:04

TI-BASIC, 15 bytes

Heck, while we're at it, might as well get a TI-BASIC answer in here.

Input format is "string":prgmNAME. Credit to Thomas Kwa for finding it first!

length(Ans)+log(Ans≠"GOOGLE

(Guide: add 1 byte for each lowercase letter replacing an upper-case one. So s/GOOGLE/google/g => +6 bytes.)

ahhhhh test cases!

"GOGGLE":prgmG
               6
"BING":prgmG
               4
"GOOGLE":prgmG
           Error
  • 20 bytes: length(Ans)/(Ans≠"google. You also have the case wrong; if uppercase is allowed it's 14 bytes. By the way, it's valid to pass arguments through Ans. – lirtosiast Sep 28 '15 at 19:37
  • AGOOGLE should give 7, correct? And you shouldn't be counting the program header in your code size, so subtract 10 bytes. – lirtosiast Sep 28 '15 at 20:48
  • ERROR: I was thinking substrings. Kindly forgive me. – Conor O'Brien Sep 28 '15 at 20:49
  • 1
    @ThomasKwa I didn't see your comment with the code. It just so happens that we both stumbled upon the same solution. However, if you believe you deserve the credit, the credit shall be yours. ^_^ (EDIT If you would read the code, it isn't the exact same thing.) – Conor O'Brien Sep 28 '15 at 22:13
  • @lirtosiast length( is two bytes, that would make your numbers 21 and 15 bytes. – Timtech Mar 29 '16 at 19:28

APL (14)

(⍴÷'google'∘≢)

Explanation:

  • : length
  • ÷: divided by
  • 'google∘≢: argument is not equal to 'google'.

gives the length of the string, which is divided by 1 if the string does not equal google (which gives the length back unchanged), or by 0 if the string does equal google (giving an error).

  • 11
    I think you don't need to count the parens, as it can be assigned to a variable without them. – jimmy23013 Sep 29 '15 at 6:06
  • Kind-of fails on single-char arguments. Fix by replacing with . Also, you can make it cooler-looking by swapping the operands of . Oh, don't forget to remove the parens. All-in-all: ≢÷≢∘'google' – Adám Jan 10 '17 at 23:08

Python 3, 30 bytes

lambda u:[len][u=='google'](u)

Indexes the 1-element function list, raising an IndexError if the u=='google' predicate is True (= 1). Such functional.

Much variants. Wow:

lambda u:[len(u)][u=='google']
lambda u:len([u][u=='google'])

If the challenge was inverted (error on everything not "google"), could save a char:

lambda u:{'google':len}[u](u)

But you already know the length, so just hardcode it.

  • works for python 2.7 too – Noodle9 Oct 1 '15 at 16:42
  • For some reason, I love this solution. – foslock Mar 26 '16 at 2:20

Haskell, 24 bytes

g s|s/="google"=length s

Output:

Main> g "google"

Program error: pattern match failure: g "google"

Main> g "bing"
4

CJam, 16 characters

{_,\"google"=!/}

This divides the length by 1 if the string is not google and by 0 otherwise. The idea is not novel, but I came up with it independently.

Try it online.

How it works

_                 Push a copy of the string on the stack.
 ,                Compute the length of the copy.
  \               Swap the length and the original string.
   "google"=      Push 1 if the string is "google", 0 otherwise.
            !     Apply logical NOT. Maps 1 to 0 and 0 to 1.
             /    Divide the length by the Boolean.
  • Interestingly enough, a full program is shorter (15 bytes): q_,\"google"=!/. Developed it before seeing this post. Note that this takes the whole input (which you seem to take anyways as a function argument). Unfortunately, you can't use it, since this asks for a function :( – Erik the Outgolfer Nov 1 '16 at 21:53

Octave, 63 bytes

I know it is longer than the Matlab solution (which would work in Octave too), but it is particularly evil. I am making an anonymous function (evil) using cell array (evil) literals (evil) containing function handles dependent on a callback function (itself, thus recursive, evil) that must be passed via argument. Then I create another anonymous that basically reduces the function to the string argument and fixes the second argument of f as f (very evil). Any sane human would never do this, because it is almost as unreadable as Perl or regex (or cjam/pyth/any other esolang).

So if the string is not 'google' the second argument of the cell array will be called which outputs the length of the string. Otherwise the first function will be called, which is passed as a callback (and passes itself as callback to itself too) which later is the function itself. The error is basically some maximum recursion depth error.

f=@(s,f){@()f(s,f),numel(s)}{2-strcmp(s,'google')}();@(s)f(s,f)
  • 2
    Those things are not evil in most languages. And this is code golf, some of the most unreadable code on the planet exists here :). Cool handle btw. – BAR Oct 2 '15 at 20:22
  • 8
    I'm only missing some eval here to make it really EVIL :-) – Luis Mendo Oct 5 '15 at 0:11

JavaScript, 25 Bytes

Nice and simple JavaScript example:

e=>e!='google'?e.length:g

If "google" is entered then it passes a ReferenceError

Example

alert((e=>e!='google'?e.length:g)('test'))

  • 2
    Wow, thanks for telling me there's a shorthand for lamda functions in javascript! – Tomáš Zato Oct 3 '15 at 17:28
  • 3
    @TomášZato Caveat: they're brand new in ES2015, so support still varies. – Anko Oct 4 '15 at 22:31

APL, 19 17 bytes

{⍵≡'google':⍟⋄≢⍵}

This is an unnamed monadic function that will throw a syntax error if the input is google. This is accomplished by attempting to take the natural logarithm of nothing.

{
 ⍵≡'google':          ⍝ If the right argument is "google"...
            ⍟⋄        ⍝ Compute log(<nothing>), which brings only sadness
              ≢⍵      ⍝ Otherwise compute the length
}

Try it online

Saved two bytes thanks to Dennis!

  • is known informally as "splat". A very appropriate name for this usage. – Adám Jan 10 '17 at 23:09

Perl, 31 29 bytes

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

-2b thanks to manatwork

Usage:

sub{$_=pop;y///c/!/^google$/}->("google")

If I could get away with a program rather than a function, the following would be valid with only 20 bytes (+1 byte command line)

$_=y///c/!/^google$/

Error is division by zero.

Explanation:

y///c returns the length, then !/^google$/ will return 0 iff input matches 'google'.

Usage:

perl -p entry.pl input.txt
  • 2
    You could make it an anonymous function: sub{…}. (Then you call it like sub{…}->("google").) – manatwork Sep 29 '15 at 8:30
  • Save 1 byte by using $_!=google instead of !/^google$/ – Gabriel Benamy Nov 1 '16 at 3:05
  • @GabrielBenamy I'm afraid != won't work to compare string... – Dada Feb 16 '17 at 16:24

Haskell - 30 characters

g"google"=error"!";g s=length s

>g "google"
 *Exception: !
>g "str"
 3
  • 6
    Why the exclamation mark for error? Wouldn't an empty string do too? – Kritzefitz Sep 28 '15 at 18:36
  • 1
    I wanted to suggest to change it to x=x;g"google"=x;g s=length s, but for some reason, <<loop>> exceptions aren't thrown in ghci. – Kritzefitz Sep 28 '15 at 18:44
  • 17
    g s|s/="google"=length s avoids the need for error – chs Sep 28 '15 at 23:30

Python 3, 35 bytes

lambda n:len(n)if n!='google'else d
  • 1
    @FryAmTheEggman actually 16 bits shorter. XD – DiegoDD Sep 28 '15 at 23:26
  • 1
    @FryAmTheEggman: Good trick but id does not work with empty string: (lambda n:len(n)*(n!='google')or d)('') – pabouk Sep 29 '15 at 9:17
  • @pabouk Quite right, thanks for pointing that out. – FryAmTheEggman Sep 29 '15 at 12:39

MUMPS, 28 bytes

g(s) q $S(s'="google":$L(s))

Usage:

>w $$g^MYROUTINE("bing")                                      
4
>w $$g^MYROUTINE("google")

<SELECT>g^MYROUTINE

Why? Well, $S[ELECT] is basically a compact multi-clause if-else statement - almost like a pattern-match in a language like Haskell or Rust. Except... unlike in Haskell or Rust, the patterns aren't checked for exhaustiveness, because the notion of "compile-time safety" is completely alien to MUMPS. So if your input is a pattern you didn't account for, you get a lovely runtime error called <SELECT>.

Ruby, 34 30 27 26

->x{x=='google'?t: x.size}

Unknown t raises exception.

->x{x=='google'?fail():x.size}

Edit: totally readable and obvious version that is shorter...

->x{x[x=~/^(?!google$)/..-1].size}

Old: Pretty similar to other ideas it seems. Will raise ArgumentError if x is 'google'.

  • 2
    Why those parenthesis? x=='google'?t: x.size – manatwork Sep 28 '15 at 18:48

R, 46 bytes

g=function(x)ifelse(x!="google",nchar(x),)

Unless I'm misreading, the original post never specified that the code had to be correct syntax.

Example:

> g("bing")
[1] 4
> g("google")
Error in ifelse(x != "google", nchar(x), ) : 
  argument "no" is missing, with no default

I never added anything for the "no" parameter of the ifelse statement so it will return an error if this parameter is evoked.

  • 7
    Here is a slightly shorter one: g=function(x)nchar(x)[[x!="google"]] – flodel Sep 29 '15 at 1:38

Java 7:53 52 Bytes

int g(String _){return"google"==_?0/0:_.length();} 

Above code will throw ArithmeticException for division by zero and for any String other than google. Worth to note that == compares reference and won't work for String Objects.

Java 8 : 29 Bytes

(Based on suggestion given in below comment)

s->s=="google"?0/0:s.length()
  • 1
    You can also use Java 8's lambda declaration: s->(s.equals("google")?null:s).length(); – h.j.k. Sep 29 '15 at 3:48
  • 2
    "Worth to note that == compares reference and won't work for String Objects." Actually, all strings are objects, so comparing strings with == in Java will generally not work (unless you're relying on string interning, which is, well, bad). Perhaps you got confused with JavaScript? – gengkev Oct 6 '15 at 0:52
  • @gengkev If they are both litterals, it will work since it is the same object that's referenced to on the String pool. The spec gives a litteral and here it is a litteral so it will work. – Yassin Hajaj Nov 21 '15 at 23:16
  • 1
    @YassinHajaj I agree that the spec gives it as a literal, but that's just an example. The function should probably perform the same if given input from stdin as well, or if the function is called from another class that's compiled separately. In any case, relying on compiler optimizations (string interning) is a poor idea, which is what I originally said. – gengkev Nov 21 '15 at 23:28

C++11, 54 (code) + 14 (#include) = 68

Well, division by zero is just undefined behaviour, which I would not call an error. So my approach.

#include<ios>
[](std::string s){return s!="google"?s.size():throw;};

usage

[](std::string s){return s!="google"?s.size():throw;}("google");
  • 1
    You can call size() to save 2 bytes. In C++14, you could also use generic lambdas and replace std::string by auto. You'd need to pass an actual std::string to it instead of a const char*. – isanae Sep 28 '15 at 23:35
  • @isanae I didn't know std::string has size() method, thanks for that. I am aware of generic lambdas in C++14, but I don't know how it would help me, since "string" is const char* and not std::string. – Zereges Sep 29 '15 at 6:38
  • 1
    @Zereges std::string has size() and length() because it's both a container and a string. As for auto, you'd call the lambda with (std::string("google")) instead of ("google"). The question only says "accepts 1 string" without specifying what a "string" is. – isanae Sep 29 '15 at 6:42
  • @isanae C++14 also has "google"s to construct an std::string :) – Quentin Sep 29 '15 at 17:47
  • @Zereges you can simply throw; to trigger std::terminate() (because there's no current exception here). – Quentin Sep 29 '15 at 17:48

JavaScript, 47 bytes

Nice and simple.

Edit: Now complies with the rules

function f(g){if(g=="google")a;return g.length}

Testing

Error thrown

function f(g){if(g=="google")a;return g.length}

alert(f("Hello"))
alert(f("google"))
alert(f("hi"))

No error thrown

function f(g){if(g=="google")a;return g.length}

alert(f("Hello"))
alert(f("bing"))
alert(f("hi"))

  • Technically, this doesn't meet the OP's specs. This function alerts the length but returns undefined. – Bungle Sep 30 '15 at 5:00
  • @Bungle How's it now? – Beta Decay Sep 30 '15 at 5:57
  • 1
    @Bungle I see. I forgot that a return was needed – Beta Decay Sep 30 '15 at 16:58
  • 1
    Using ES6's arrow functions and ternary operator (instead of if), you can squeeze that a bit more :) – Carles Alcolea Oct 1 '15 at 21:09
  • 1
    @BetaDecay Originality first; I respect that. – Carles Alcolea Oct 2 '15 at 1:08

C, 66 48

Original:

int l(long*s){return strlen(s)/((*s&~(-1L<<56))!=0x656c676f6f67);}

Using OSX gcc,
l("duck"); returns 4,
l("google"); causes Floating point exception: 8.

On other platforms, the constants may need to be adjusted for endianness.

Shorter:

less trickyness, same results.

 l(int*s){return strlen(s)/!!strcmp(s,"Google");}
  • Wow, that is some interesting logic there. If I understand the golfy part right, you are somehow shifting the first six chars to fit into a single, giant number (almost like a hash), which, because of the stack being little-endian, ends up being "google", but backwards (0x656c676f6f67 = elgoog). I think this answer needs an explanation for those of us who appreciate this kind of crazy low-level stuff. – Braden Best Sep 29 '15 at 21:46
  • You basically have it. It simply casts the memory storing the string into a 64 bit number. Endianness makes it 'backward' on x86 architectures. The text only occupies 7 bytes, so the mask just hides whatever may be next in memory. Its a fun trick, but I think '!!strcmp(s,"google")' is actually shorter. – AShelly Sep 30 '15 at 0:25
  • 1
    Anyways, +1. Definitely. Also, I think you can shorten it by removing the int , that's 4 characters. – Braden Best Sep 30 '15 at 2:37
  • After some typing, I figured it out! If char *, with units of 8-bits, is casted to long *, with units of 64-bits, without being properly reallocated, the data in those 8 bytes of heap space becomes corrupted, and treated as a single number (8*8 = 64). That's why you get the first 6 chars, + NUL + garbage. That is very clever. Dangerous, too. Wonder why it doesn't segfault. That 8th garbage byte is out of bounds, no? – Braden Best Sep 30 '15 at 3:12
  • I looked at your analysis. You are correct, the shift should have been 56, not 54. Also, I wouldn't use the word corrupted. The memory is the same, the bits are just interpreted differently. Technically, accessing the garbage byte is undefined behavior, and could actually segfault. Practically, that byte almost certainly resides in the same legal memory block as the rest of the string, and generally these blocks (heap, stack, constants) are allocated in word sized units at a minimum. So the memory belongs to the program, it just contains something other than the string. – AShelly Sep 30 '15 at 18:07

Ruby, 29 bytes

I first came up with something very similar to @Borsunho's first attempt, but mine was slightly longer and he posted his before I was done. Came up with this before his 30 bytes edit :)

->s{s[/^(?!google$).*/].size}

Usage examples:

$ irb
2.2.1 :001 > f = ->s{s[/^(?!google$).*/].size}
 => #<Proc:0x007fa0ea03eb60@(irb):1 (lambda)> 
2.2.1 :002 > f[""]
 => 0 
2.2.1 :003 > f["bing"]
 => 4 
2.2.1 :004 > f["google"]
NoMethodError: undefined method `size' for nil:NilClass
  from (irb):1:in `block in irb_binding'
  from (irb):4:in `[]'
  from (irb):4
  from /Users/daniel/.rvm/rubies/ruby-2.2.1/bin/irb:11:in `<main>'

edit: Two years and some Ruby versions later

Ruby, 25 bytes

->s{+s[/^(?!google$).*/]}

Replaced String#size with the new unary plus. Try it online!

  • Neat, I couldn't get this to work ( I didn't came up with leaving ^ outside the matchgroup). – Borsunho Sep 28 '15 at 18:00
  • @Borsunho I have to admit I just "brute forced" the regex untill I got the result that I wanted :) I think the .* at the end is what makes it work. – daniero Sep 28 '15 at 18:07
  • Breaks if the input string has multiple lines and contains google on its own line. I think /\A(?!google\Z).*/m fixes it (at the cost of three bytes, though). ^ and $ match the beginning and end of lines, while \A and \Z match the beginning and end of the string as a whole. – histocrat Sep 28 '15 at 18:30
  • @histocrat but I don't think you can google strings with multiple lines ;) – daniero Sep 28 '15 at 19:01

><>, 55 bytes

i:0(?v
31&l~<v0"google"~~.?%2l
$v?(2l<S?*=2l=6:+={
&<;n

Figured I'd give this a go, not my best golfing attempt or algorithm, though. Not a function per se, but I think that this should still qualify. I'll see if I can edit in a better version.

If you're allowed to print the length and then error, here's a 46 byte solution:

i:0(?v
2lnl~<v0"google";?%
$;?(2l<S?*=2l=6:+={

49 byte previous solution of this nature:

i:0(?v
l0nl~<v;!?=7
:;?(2l<S?*=2l=6:+=@@g3
elgoog

I'm happy to put up an explanation if there's any interest, and please let me know if there's anything wrong with my answer or if you have golfing suggestions.

Javascript ES6, 51 27 25 bytes

Hi, I'm new to code golf so this can probably be golfed much more, but here it goes:

_=>_=="google"?a:_.length

g=_=>_=="google"?a:_.length

g=_=>{if("google"==_)throw Error();return _.length}

and some test:

(_=>_=="google"?a:_.length)("bing")//4
(_=>_=="google"?a:_.length)("google")// Error: a is not defined

g("bing")// returns 4
g("google")// Error: a is not defined

Edit: Added ? to replace if and replace Error with an undefined object.

Edit 2: I realized my byte count was wrong, and removed the g=

GolfScript, 14 16 Characters

{.,\'google'=!/}

Like many others, simply compares the input to 'google' and divides the length by the inverse of the result.

Example programs:

  • @Dennis I see your point. In it's original form it wasn't exactly reusable (you couldn't, say apply the code over an a list). Also I didn't realize that you had written a virtually identical answer in CJam well before I posted this (actually I was only vaguely aware of CJam as a language until now). +1 for your solution, too. – p.s.w.g Sep 30 '15 at 4:34

Stuck, 16 Bytes

s_l1u"google"=-/

Following a similar method to most people, will cause a divide by 0 error on "google" being input.

Windows Batch, 118 characters

IF /I "%string%"=="google" exit
echo %string%> string.txt
for %%? in (string.txt) do ( SET /A stringlength=%%~z? - 2 )

Output is %stringlength%.

Full code:

@echo off
del string.txt
cls
echo Type your string
echo.
set /p string=String:
IF /I "%string%"=="google" goto err
echo %string%> string.txt
for %%? in (string.txt) do ( SET /A stringlength=%%~z? - 2 )
cls
echo %stringlength%
pause
del string.txt
:err
color c
echo There seems to be an error with your input...
pause>nul

Modified from Joshua Honig's answer, here.

protected by mbomb007 Sep 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).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.