How long is this string?

-13

It's strange this question hasn't been asked yet, so here it is:

Calculate the length of a string given through STDIN

Rules

  • As said, your string will be given through STDIN, not via command line arguments

  • Print the length of the string to STDOUT

  • Only ASCII chars will be given, and all printable ASCII chars count!

  • This is a , so the answer with the shortest length wins!

Good Luck and have fun!

Mega Man

Posted 2018-05-28T13:05:56.353

Reputation: 1 379

every ASCII char counts! Even control characters. Can you provide an example of what you mean ? – The random guy – 2018-05-28T13:07:29.023

@Therandomguy here you are – Mega Man – 2018-05-28T13:10:17.933

Does "you^Z^Z^Z" mean that actual 9-byte printable-ASCII string, or does ^Z mean some control character and the string has length 6? – Luis Mendo – 2018-05-28T13:12:44.683

^Z is meant like a backspace char, this rule doesn't seem to be good, because it is impossible on many languages (strange STDIN limitations) – Mega Man – 2018-05-28T13:14:24.443

1In that case, you should probably restrict to printable ASCII. "Most ASCII chars counts" is ambiguous – Luis Mendo – 2018-05-28T13:16:52.710

@LuisMendo sorry for all that chaos – Mega Man – 2018-05-28T13:17:35.750

Obviously most people don't like too easy challenges, but it's valid. (although we already have "add two numbers" and "is that number a prime") – user202729 – 2018-05-28T13:18:08.227

@user202729 I would consider this another reference challenge, like Hello, World! – Mega Man – 2018-05-28T13:21:02.327

13When the main difficulty is the input format or means, rather than the actual computations, it is usually a sign of a not very interesting challenge – Luis Mendo – 2018-05-28T13:22:51.280

1What about languages that cannot use STDIN? – Adám – 2018-05-28T13:26:49.673

@Adám I guess they can't compete in this challenge. A lot of challenges aren't accessible to some languages due to their restrictions. – Kevin Cruijssen – 2018-05-28T13:30:03.420

@Adám Which language can't use STDIN? – Mega Man – 2018-05-28T13:37:22.527

@MegaMan ECMAScript, in-browser JavaScript, TI-Basic, Operation Flashpoint scripting language, … – Adám – 2018-05-28T13:47:53.623

1and all printable ASCII chars count! what do non-printable ones? – l4m2 – 2018-05-28T14:44:42.207

This is likely more-or-less trivial in essentially any language that can be used for the challenge (i.e., supports stdin), unless you specifically disallow the use of 'length' or 'shape' intrinsics. – Jeff Zeitlin – 2018-05-28T15:14:02.620

3It's not entirely clear how inputs should be taken, ie. given "" on stdin is it an empty string, two characters or is it up to the language (in that case would " be valid input)? – ბიმო – 2018-05-28T15:19:03.463

@BMO - I have assumed that the quotes count and also that they can be in the string. If not then I half my byte count from 2 to 1 :-) It should really be clarified. – ElPedro – 2018-05-28T16:41:47.060

@BMO In my opinion it's by far the most natural to say the string is the "raw" contents of standard in. Taking source code as input doesn't make much sense for this challenge. – Jakob – 2018-06-05T02:24:29.550

I think I should rather close this question. – Mega Man – 2018-06-07T16:59:55.107

Answers

7

Shakespeare Programming Language, 156 bytes

Thanks JoKing for nice trick with [Exeunt].

,.Ajax,.Page,.Act I:.Scene I:.[Exeunt][Enter Ajax and Page]Ajax:Open mind Be you nicer zero?Page:If soyou be the sum ofa cat you.If solet usact I.Open heart

Try it online!

user202729

Posted 2018-05-28T13:05:56.353

Reputation: 14 620

2You is the sum... I'm not sure The Bard would approve of your grammar – Luis Mendo – 2018-05-28T13:29:14.337

What is that "nice trick with exeunt"? Shouldn't [Exeunt] be unnecessary since no one is on the stage? – pppery – 2019-11-07T20:11:56.077

@pppery (Sorry for late reply) on subsequent iterations there are people on the stage, and it's an error when people enter twice. [Exeunt] doesn't throw any error when there's no one. (Check diff between revision 3 and 4) – user202729 – 2019-11-20T06:46:08.290

4

Golfscript (1 byte)

,

And that's why this question hadn't already been asked.

Peter Taylor

Posted 2018-05-28T13:05:56.353

Reputation: 41 901

3

05AB1E, 1 byte

g

Try it online.

Explanation:
(As if it would be necessary..)

     # Implicit input from STDIN
g    # Length
     # Implicit output to STDOUT

Kevin Cruijssen

Posted 2018-05-28T13:05:56.353

Reputation: 67 575

3

Seems to give the wrong result for """.

– ბიმო – 2018-05-28T14:05:48.690

@BMO Hmm, you're right. Not sure how to fix that, though (but I will ask around in the 05AB1E chat). One or two double quotes works fine. Any amount of double quotes and another character works fine as well. But three or more double-quotes not anymore. – Kevin Cruijssen – 2018-05-28T16:47:56.110

1

@BMO Inputting three double quotes would need to be done by surrounding it with three double quotes, so """"""""" would result in 3. This is because three double quotes denote multiline strings.

– Adnan – 2018-05-28T19:00:14.037

3

Java 8, 63 bytes

A lambda taking empty input and throwing IOException.

n->{int c=0;while(System.in.read()>=0)c++;System.out.print(c);}

Try It Online

Jakob

Posted 2018-05-28T13:05:56.353

Reputation: 2 428

3

brainfuck, 163 bytes

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

Try it online!

Somebody had to make this a little interesting.

Explanation:

,[>+<,]>

This is a modified cat program that, rather than outputting each read value, increments the 2nd cell each time a value is read.

The entire rest of the program is for outputting a cell's value as a number rather than an ASCII codepoint.

Skidsdev

Posted 2018-05-28T13:05:56.353

Reputation: 9 656

2

Hexagony, 11 bytes

,~<@!"/>"){

Try it online!

More readable version:

  , ~ <
 @ ! " /
> " ) { . 
 . . . .
  . . .

Adyrem

Posted 2018-05-28T13:05:56.353

Reputation: 521

1

Pyth, 2 bytes

lz

Explanation

l          #length of
 z         #input

Try it online!

ElPedro

Posted 2018-05-28T13:05:56.353

Reputation: 5 301

@LuisMendo - Not sure. It depends if surrounding quotes should be counted as part of the text or not. Also without the z it fails if a quoted string contains a quote within the string. – ElPedro – 2018-05-28T14:01:15.520

Ah, good point. Deleting suggestion then – Luis Mendo – 2018-05-28T14:02:05.240

1

Haskell, 25 20 bytes

-5 bytes for making this a function only (initially thought that it has to be a full program)

interact$show.length

Try it online!

ბიმო

Posted 2018-05-28T13:05:56.353

Reputation: 15 345

1

Brain-Flak + -a flag, 6 bytes

Even Brain-Flak has a built-in for this challenge...

([]<>)

Try it online!

Without using [] but still rather simple (10 bytes): ({<{}>()})

ბიმო

Posted 2018-05-28T13:05:56.353

Reputation: 15 345

1

Whitespace, 73 64 bytes

[S S S N
_Push_0][N
S S N
_Create_Label_LOOP][S N
S _Duplicate][S N
S _Duplicate][T N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve][S S S T  S T T   S T T   S N
_Push_182][T    S S T   _Subtract][N
T   S S N
_If_0_jump_to_Label_PRINT_AND_EXIT][S S S T N
_Push_1][T  S S S _Add][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT_AND_EXIT][T N
S T _Print_to_STDOUT]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Input requires a trailing , because Whitespace has no way to tell when the input-characters are complete. Whitespace only has two STDIN inputs: integer or character. A full string should be inputted one by one, but Whitespace doesn't know when it has all. So perhaps this answer is non-competing due to the restriction of Whitespace, but I've chosen a character outside the printable ASCII range to add as leading character for inputs, so the program knows when to stop and output the length.

Try it online (with raw spaces, tabs and new-lines only).

Explanation in pseudo-code:

Integer counter = 0
Start LOOP:
  Integer input = STDIN as character
  If(input == '¶')
    Jump to function PRINT_AND_EXIT
  counter = counter + 1
  Jump to next iteration of LOOP

function PRINT_AND_EXIT:
  Print counter as integer to STDOUT

Example input: acb¶

Command        Explanation                 Stack        HEAP                    STDIN   STDOUT  STDERR

SSSN           Push 0                      [0]
NSSN           Create Label_LOOP           [0]
 SNS           Duplicate top (0)           [0,0]
 SNS           Duplicate top (0)           [0,0,0]
 TNTS          Read STDIN as character     [0,0]        {0:97}                  'a'
 TTT           Retrieve                    [0,97]       {0:97}
 SSSTSTTSTTSN  Push 182                    [0,97,182]   {0:97}
 TSST          Subtract top two (97-182)   [0,-85]      {0:97}
 NTSSN         If 0: Jump to Label_EXIT    [0]          {0:97}
 SSSTN         Push 1                      [0,1]        {0:97}
 TSSS          Add top two (0+1)           [1]          {0:97}
 NSNN          Jump to Label_LOOP          [1]          {0:97}

 SNS           Duplicate top (1)           [1,1]        {0:97}
 SNS           Duplicate top (1)           [1,1,1]      {0:97}
 TNTS          Read STDIN as character     [1,1]        {0:97,1:99}             'c'
 TTT           Retrieve                    [1,99]       {0:97,1:99}
 SSSTSTTSTTSN  Push 182                    [1,99,182]   {0:97,1:99}
 TSST          Subtract top two (99-182)   [1,-83]      {0:97,1:99}
 NTSSN         If 0: Jump to Label_EXIT    [1]          {0:97,1:99}
 SSSTN         Push 1                      [1,1]        {0:97,1:99}
 TSSS          Add top two (1+1)           [2]          {0:97,1:99}
 NSNN          Jump to Label_LOOP          [2]          {0:97,1:99}

 SNS           Duplicate top (2)           [2,2]        {0:97,1:99}
 SNS           Duplicate top (2)           [2,2,2]      {0:97,1:99}
 TNTS          Read STDIN as character     [2,2]        {0:97,1:99,2:98}        'b'
 TTT           Retrieve                    [2,98]       {0:97,1:99,2:98}
 SSSTSTTSTTSN  Push 182                    [2,98,182]   {0:97,1:99,2:98}
 TSST          Subtract top two (98-182)   [2,-84]      {0:97,1:99,2:98}
 NTSSN         If 0: Jump to Label_EXIT    [2]          {0:97,1:99,2:98}
 SSSTN         Push 1                      [2,1]        {0:97,1:99,2:98}
 TSSS          Add top two (2+1)           [3]          {0:97,1:99,2:98}
 NSNN          Jump to Label_LOOP          [3]          {0:97,1:99,2:98}

 SNS           Duplicate top (3)           [3,3]        {0:97,1:99,2:98}
 SNS           Duplicate top (3)           [3,3,3]      {0:97,1:99,2:98}
 TNTS          Read STDIN as character     [3,3]        {0:97,1:99,2:98,3:182}  '¶'
 TTT           Retrieve                    [3,182]      {0:97,1:99,2:98,3:182}
 SSSTSTTSTTSN  Push 182                    [3,182,182]  {0:97,1:99,2:98,3:182}
 TSST          Subtract top two (182-182)  [3,0]        {0:97,1:99,2:98,3:182}
 NTSSN         If 0: Jump to Label_EXIT    [3]          {0:97,1:99,2:98,3:182}

NSSSN          Create Label_EXIT           [3]          {0:97,1:99,2:98,3:182}
 TNST          Print as integer to STDOUT  []                                          3
                                                                                               error

Stops program with error: No exit defined.

Kevin Cruijssen

Posted 2018-05-28T13:05:56.353

Reputation: 67 575

1

APL+WIN, 2 bytes

Prompts for character string input then counts characters:

⍴⍞

Graham

Posted 2018-05-28T13:05:56.353

Reputation: 3 184

Try it online! – Adám – 2018-05-28T21:44:58.013

@Adám Thanks. Fixed. – Graham – 2018-05-29T08:29:43.047

1

Keg, 3 bytes

?!.

Well, I can't golf this program well.

TIO

user85052

Posted 2018-05-28T13:05:56.353

Reputation:

0

Octave, 14 bytes

nnz(input(''))

Try it online!

Luis Mendo

Posted 2018-05-28T13:05:56.353

Reputation: 87 464

0

R, 23 bytes

cat(nchar(readLines()))

Try it online!

JayCe

Posted 2018-05-28T13:05:56.353

Reputation: 2 655

0

Retina, 3 bytes

s`.

Try it online!

This isn't even technically a built-in function, but it is a central feature of the language: counting matches of a regular expression, in this case . (wildcard matching any character). The ` makes Retina treat the character(s) preceding it in the line as configuration, so s activates SingleLine mode, which makes . match newlines also, because they are part of printable ASCII.

NinjaBearMonkey

Posted 2018-05-28T13:05:56.353

Reputation: 9 925

0

Batch, 182 bytes

@set s=
@set/ps=
@set "t=%s:"=""%"
@if "%t:"=""%"=="""=""""" goto g
@for %%s in ("%s:"=%" "%t%")do @echo(%%~s>>_
@for %%s in (_)do @set s=%%~zs
@del _
:g
@cmd/cset/as/2-2*!!s

Testing for the empty string without breaking when quotes were present was cumbersome! Explanation:

@set s=

Clear s as set/p leaves s unchanged if the input was empty.

@set/ps=

Take input on STDIN into s.

@set "t=%s:"=""%"

Try to quote all of the quotes in s. However, if s is empty, Batch throws a wobbly, and sets t to "="" instead, which still has an odd number of quotes.

@if "%t:"=""%"=="""=""""" goto g

Quote all of the quotes in t, and compare the result to ""="""". This can only happen if s was empty, in which case we skip the measurement step.

@for %%s in ("%s:"=%" "%t%")do @echo(%%~s>>_

Print s without quotes and s with quoted quotes on separate lines to a temporary file. The ( is needed in case s only contains quotes.

@for %%s in (_)do @set s=%%~zs

Obtain the length of the temporary file.

@del _

Delete the temporary file.

:g

Jump here if the input was empty.

@cmd/cset/as/2-2*!!s

Halve and subtract 2 from the length of the temporary file. However if the input was empty then s will be treated as the numeric value zero, and the result of the expression is then zero as desired.

117 bytes without empty string support:

@set/ps=
@for %%s in ("%s:"=%" "%s:"=""%")do @echo(%%~s>>_
@for %%s in (_)do @set s=%%~zs
@del _
@cmd/cset/as/2-2

93 bytes if support for "s is not necessary (84 bytes without " or empty string support):

@set s=
@set/ps=
@set n=0
:l
@if not "%s%"=="" set/an+=1&set "s=%s:~1%"&goto l
@echo %n%

Empty strings and quotes can even be handled for 212 bytes without resorting to file length builtins:

@set s=
@set/ps=
@set "t=%s:"=""%"
@set n=0
@if "%t:"=""%"=="""=""""" goto g
:l
@set/an+=1
@set "s=%t:~,1%%t:~,1%"
@if "%s%" neq """" set "t=.%t%"
@set "t=%t:~2%"
@if not "%t%"=="" goto l
:g
@echo %n%

Here after quoting the quotes in s we have to be careful to double the first character of t in case it is a quote, then if it is not then prefix a dummy character to t so that the first two characters may be safely removed. This ends up counting the quoted quotes as single characters again.

Neil

Posted 2018-05-28T13:05:56.353

Reputation: 95 035

0

Ruby, 16 Bytes

This was rather easy.

puts gets.length

needs no explanation ;)

Windmill Cookies

Posted 2018-05-28T13:05:56.353

Reputation: 601

0

Perl 6,  15  14 bytes

slurp.codes.say

Try it

say +$*IN.comb

Try it


  • slurp reads everything
  • codes gets the number of Unicode codepoints
    (this is different than chars for \r\n)
  • say print the .gist with trailing newline
    (put could have been used, which just adds the newline)
  • &prefix:« + » converts to Numeric
  • $*IN is STDIN
  • comb splits its input into a sequence of characters
    (Which when converted to Numeric returns a count)

Brad Gilbert b2gills

Posted 2018-05-28T13:05:56.353

Reputation: 12 713

0

Python 3, 19 bytes

print(len(input()))

Try it online!

Jitse

Posted 2018-05-28T13:05:56.353

Reputation: 3 566

0

W s, 1 byte

k

Explanation

% s: we have to read from STDIN.
% Implicitly prepend an input
k % (k)ount the number of items in this thing
% Implicit output

How do I use the parameter?

The cli param system is quite weird (to allow people to type less), so here is an example of how it is used:

$ ..\python W.py code.w [] s
'Hello'
Code: k
#0: a []
#1: k ['a[0]']
out: lambda a:mylen(a[0])
5

user85052

Posted 2018-05-28T13:05:56.353

Reputation: