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: