-13
\$\begingroup\$

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!

\$\endgroup\$
  • 1
    \$\begingroup\$ In that case, you should probably restrict to printable ASCII. "Most ASCII chars counts" is ambiguous \$\endgroup\$ – Luis Mendo May 28 '18 at 13:16
  • 13
    \$\begingroup\$ When 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 \$\endgroup\$ – Luis Mendo May 28 '18 at 13:22
  • 1
    \$\begingroup\$ What about languages that cannot use STDIN? \$\endgroup\$ – Adám May 28 '18 at 13:26
  • 1
    \$\begingroup\$ and all printable ASCII chars count! what do non-printable ones? \$\endgroup\$ – l4m2 May 28 '18 at 14:44
  • 3
    \$\begingroup\$ It'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)? \$\endgroup\$ – ბიმო May 28 '18 at 15:19

19 Answers 19

7
\$\begingroup\$

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!

\$\endgroup\$
  • 1
    \$\begingroup\$ You is the sum... I'm not sure The Bard would approve of your grammar \$\endgroup\$ – Luis Mendo May 28 '18 at 13:29
  • \$\begingroup\$ What is that "nice trick with exeunt"? Shouldn't [Exeunt] be unnecessary since no one is on the stage? \$\endgroup\$ – pppery Nov 7 at 20:11
  • \$\begingroup\$ @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) \$\endgroup\$ – user202729 Nov 20 at 6:46
4
\$\begingroup\$

Golfscript (1 byte)

,

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

\$\endgroup\$
3
\$\begingroup\$

05AB1E, 1 byte

g

Try it online.

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

     # Implicit input from STDIN
g    # Length
     # Implicit output to STDOUT
\$\endgroup\$
  • 3
    \$\begingroup\$ Seems to give the wrong result for """. \$\endgroup\$ – ბიმო May 28 '18 at 14:05
  • \$\begingroup\$ @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. \$\endgroup\$ – Kevin Cruijssen May 28 '18 at 16:47
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ – Adnan May 28 '18 at 19:00
3
\$\begingroup\$

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

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Hexagony, 11 bytes

,~<@!"/>"){

Try it online!

More readable version:

  , ~ <
 @ ! " /
> " ) { . 
 . . . .
  . . .
\$\endgroup\$
1
\$\begingroup\$

Pyth, 2 bytes

lz

Explanation

l          #length of
 z         #input

Try it online!

\$\endgroup\$
  • \$\begingroup\$ @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. \$\endgroup\$ – ElPedro May 28 '18 at 14:01
  • \$\begingroup\$ Ah, good point. Deleting suggestion then \$\endgroup\$ – Luis Mendo May 28 '18 at 14:02
1
\$\begingroup\$

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): ({<{}>()})

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

APL+WIN, 2 bytes

Prompts for character string input then counts characters:

⍴⍞
\$\endgroup\$
  • \$\begingroup\$ Try it online! \$\endgroup\$ – Adám May 28 '18 at 21:44
  • \$\begingroup\$ @Adám Thanks. Fixed. \$\endgroup\$ – Graham May 29 '18 at 8:29
1
\$\begingroup\$

Keg, 3 bytes

?!.

Well, I can't golf this program well.

TIO

\$\endgroup\$
0
\$\begingroup\$

Octave, 14 bytes

nnz(input(''))

Try it online!

\$\endgroup\$
0
\$\begingroup\$

R, 23 bytes

cat(nchar(readLines()))

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

Ruby, 16 Bytes

This was rather easy.

puts gets.length

needs no explanation ;)

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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)
\$\endgroup\$
0
\$\begingroup\$

Python 3, 19 bytes

print(len(input()))

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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