13
\$\begingroup\$

Given a string s and a non-negative number n less than the length of s, output the character at the n-th position of s.

0-indexing and 1-indexing are allowed. For 1-indexing, n will be positive and less than or equal to the length of s.

s will consist of printable characters only.

Any reasonable input/output is permitted. Standard loopholes apply.

Testcases (0-indexing):

n s        output
0 "abcde"  a
1 "abcde"  b
2 "a != b" !
3 "+-*/"   /
4 "314159" 5

Testcases (1-indexing):

n s        output
1 "abcde"  a
2 "abcde"  b
3 "a != b" !
4 "+-*/"   /
5 "314159" 5

This is , so shortest answer in bytes wins.

\$\endgroup\$
  • 13
    \$\begingroup\$ I downvoted this because it's​ not really a programming or golfing challenge; all that's essentially being asked here is which language has the shortest built-in​ for the job. \$\endgroup\$ – Shaggy May 13 '17 at 14:11
  • 15
    \$\begingroup\$ @Shaggy Same for many other simple challenges like adding two numbers, testing if a number is prime or printing "Hello, World!". While these are boring in many languages that can do them out of the box, they can be interesting challenges for more primitive languages that have to roll their own implementation. Plus, anything more complicated is usually too much to ask of those languages, so it's nice to have an outlet for them. If trivial challenges bore you, try doing them in a nontrivial language. \$\endgroup\$ – Martin Ender May 13 '17 at 14:15

65 Answers 65

1
\$\begingroup\$

Python 3, 28 bytes

print(input()[int(input())])
\$\endgroup\$
1
\$\begingroup\$

Axiom, 1 byte

.

1-Indexing... string.index is the value of string at index some test

(5) -> "123".6
   >> Error detected within library code:
   index out of range
    protected-symbol-warn called with (NIL)

(5) -> "123".0
   >> Error detected within library code:
   index out of range
protected-symbol-warn called with (NIL)

(5) -> ["123".i  for i in 1..3]
   (5)  [1,2,3]
                                                     Type: List Character

Where you see Axiom warn for index out of space too

\$\endgroup\$
  • \$\begingroup\$ Snippets are not allowed. Only functions/full programs are allowed. \$\endgroup\$ – Leaky Nun May 13 '17 at 14:20
  • \$\begingroup\$ @LeakyNun I can not see it as operator? (and so one function) \$\endgroup\$ – RosLuP May 13 '17 at 14:21
  • 2
    \$\begingroup\$ @LeakyNun that operator has already a name '.' Why I have to call in a different way? \$\endgroup\$ – RosLuP May 13 '17 at 14:24
  • 2
    \$\begingroup\$ @StephenS We're accepting the names of built-in functions as function submissions, so I don't see why we shouldn't accept the names of built-in operators (which are functions, just usually with different syntax). \$\endgroup\$ – Martin Ender May 13 '17 at 14:46
  • 2
    \$\begingroup\$ I think we've already discussed a lot of related questions on Meta (although I haven't found one that addresses this situation specifically), and IIRC a function submission has to be a function value. So in Haskell, for example, + isn't a valid solution to "add 2 numbers", but (+) is. \$\endgroup\$ – user62131 May 13 '17 at 17:28
1
\$\begingroup\$

TI-Basic, 14 bytes

Prompt Str0,N
sub(Str0,N,1

Returns the Nth 1-indexed character of the string.

Noncompeting 10 bytes:

Prompt N
sub(Ans,N,1

run with: "string":prgmNAME then input the number. I can't see the upvote/downvote ratio of this meta post on whether different input types are allowed, and it doesn't say in the tag-wiki, so I'm assuming they aren't.

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

brainfuck, 17 bytes

...because why not?

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

Try it online!

Uses 0-indexing, takes number in unary, n separated from s by .

This separates n from s with a newline.

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

J-uby, 3 bytes

:[]

[] is the subscripting operator. Example run:

irb(main):001:0> f = :[]
irb(main):002:0> f.call("string", 2)
=> "r"
\$\endgroup\$
1
\$\begingroup\$

k (kona), 0 bytes (noncompeting); 1 byte

In K, list access (as function application) is implicit. As such, we can do

q)"abcdef"0 
"a" 

But that's not really in the spirit of things, so we'll make the application of 0 on "abcdef" explicit for 1 byte:

q)"abcdef"@0
"a"
\$\endgroup\$
1
\$\begingroup\$

Java 8, 18 17 12 bytes

s->s::charAt

-5 bytes saved thanks to @Jakob.

Try it here.

Java 7, 43 bytes

char c(String s,int n){return s.charAt(n);}

Try it here.

Both 0-indexed.

\$\endgroup\$
  • \$\begingroup\$ Can you use currying i.e. s->n->... to save a byte? And does Java not have indexers i.e. s[n]? \$\endgroup\$ – TheLethalCoder May 15 '17 at 10:42
  • 1
    \$\begingroup\$ In C# you'd do Func<string, Func<int, char>> so something similar I assume. \$\endgroup\$ – TheLethalCoder May 15 '17 at 11:43
  • 1
    \$\begingroup\$ Since you're already currying, save another 5 bytes with a method reference: s->s::charAt. \$\endgroup\$ – Jakob Aug 9 '17 at 14:16
  • 1
    \$\begingroup\$ Sure! It's a simple change: TIO \$\endgroup\$ – Jakob Aug 9 '17 at 15:06
  • 1
    \$\begingroup\$ The method reference essentially extracts the charAt method from String s. s::charAt has the same type as your inner lambda: Function<Integer, Character>. \$\endgroup\$ – Jakob Aug 9 '17 at 15:08
0
\$\begingroup\$

C, 18 Bytes

#define f(s,n)s[n]

Try it online

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

PHP, 22 Bytes

<?=$argv[1][$argv[2]];

Try it online!

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

QBIC, 8 bytes

?_s;,:,1

Explanation:

?     PRINT
_s    Substring(in$, start, length)
  ;   Reads a string from the cmd line as in$
  ,:  Reads an int from the command line as start
  ,1  One character
      Statement delimeter | is auto-added at EOF.

This is 1-based. It uses QBIC's new ability to inline ; and :. Previously, to get s and n, you needed to do this:

;:?_sA,a,1

That would create the assignment of a cmd line arg to A$ and a resp. Now we can skip assignment: the interpreter extracts the assignment and moves those to the top of the script.

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

Fireball, 3 bytes

1-indexed.

╡1╞

Explanation:

╡         Get the first n characters of the input
 1╞       Get the last character of the that

Alternatively, for 4 bytes:

╡r↔♥

Explanation:

╡      Get the first n characters of the input
 r     Reverse
  ↔♥   Get the first character
\$\endgroup\$
0
\$\begingroup\$

Perl 6, 18 bytes

{substr $^a,$^b,1}

I'm a little surprised it can't be done shorter. By me, anyway.

\$\endgroup\$
  • \$\begingroup\$ could you remove the space before the first $? Not too familiar with Perl \$\endgroup\$ – Cyoce May 25 '17 at 5:19
  • \$\begingroup\$ Nope. Perl 6 requires whitespace in many places that Perl 5 doesn't. \$\endgroup\$ – Sean May 25 '17 at 6:44
  • \$\begingroup\$ that seems very un-Perl-like if that's a thing \$\endgroup\$ – Cyoce May 25 '17 at 6:53
0
\$\begingroup\$

Axiom,61 bytes

f(s:String,n:PI):Union(Character,Complex INT)==(n>#s=>%i;s.n)

1-Indexing; it return the required char or it return the %i=sqrt(-1) for error if n> lenght(s) Some test

(4) -> [f("123",i) for i in 1..10]
   (4)  [1,2,3,%i,%i,%i,%i,%i,%i,%i]
                              Type: List Union(Character,Complex Integer)
(5) -> f("123", 0)
   Conversion failed in the compiled user function f .
   Cannot convert from type Integer to PositiveInteger for value
   0

instead of doing less (few characters) instead of do more (more cicle) instead to do fast... to do the right

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

LLVM IR, 72 bytes

define i8*@a(i8*,i64){
entry:%2=getelementptr i8,i8*%0,i64%1
ret i8*%2
}

Takes a (string, index) (0-indexed) as argument, where string is a c-string. Returns an i8* (char*) which points to the desired char. I can't directly move the getelementptr with the ret instruction as %0 and %1 are function-local and therefore need their own instruction

Try it online!

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

PowerShell, 18 Bytes

param($s,$i)$s[$i]

indexes into param 1 ($s) using param 2 ($i)

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

Perl 6, 15 bytes

{$^s.comb[$^n]}

Try it

Expanded:

{ # bare block lambda with placeholder parameters 「$n」 and 「$s」

  $^s      # declare second parameter
  .comb\   # split it into graphemes
  [ $^n ]  # get the value indexed by the first parameter
}
\$\endgroup\$
0
\$\begingroup\$

Groovy 11 bytes

{s,n->s[n]}

0-indexed.

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

Charcoal, 3 bytes

§SN

Explanation

§     At index
 S   Input string
   N Input number

Try it online!

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

APL (Dyalog), 1 byte

(Index) or (Pick)

Try them online!

They only differ for higher rank arrays and nested arrays:

2⌷A will choose the second element or second row, leaving any nesting
2⊃A will pick the second element, and attempt to remove one level of nesting

2 3⌷A will choose the element at row 2 column 3
2 3⊃A will pick the third element of the second element

(⊂2 3)⌷A will choose the second and third elements or rows
(⊂2 3)⊃A will pick the element at row 2 column 3

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

Swift - 53 bytes

func f(a:String,i:Int){print(Array(a.characters)[i])}

A function f that can be used as f(a: "abcdef",i: 3). It is 0-indexed.

Check it out!

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

Chip, 114 bytes

*Z
,x.z.
`@z\{Aa
,x.|*
`@z\{Bb
,x.|
`@z\{Cc
,x.|*
`@z\{Dd
,x.|
`@z\{Ee
,x.|*
`@z\{Ff
,x.|
`@z\{Gg
,x.|*
`@z\{H
S{*

The first byte of input is a 0-based index, the remainder is the string to process: \x02abcde.

Try it online!
In this TIO, a newline character is the index, which means an index of 0x0a = 10.

Test cases!
These use hex input + printf to make it clearer what's happening.

How does it work?

S{*

This suppresses output for all bytes, by default. If powered, this can be overridden. It is a not-gate based on an xor-gate ({).

Aa, Bb, Cc, etc.

These relay the input to the output for every byte, unless suppressed. Note that the h is missing, this is because we never need to output something with the high bit set.

,x.
`@z\{D

This is the real meat of it all. There are eight of these, one for each bit of the index (a one-byte index means that indexes are not able to be specified above 255). This reads in the index on the first cycle only with switches (\). The index bits have been flipped with an xor gate ({), which is almost negation. Then, for each character of the string, this value is incremented via some half-adders (@). When this value is incremented from 0xff to 0x00, it uses the carry from the high bit to unsuppress output for that character, meaning that it is printed.

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

Ruby, 11 bytes

->n,s{s[n]}

Try it online!

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

Pyth - 3 bytes

@wE

Try it here

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

RProgN 2, 1 byte

ü

Just a builtin!

Try it online!

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

SmileBASIC 3, 17 bytes

Woo! String indexing!

DEF A S,N?S[N]END

Defines a command A to print the result. Uses 0-indexing. Call like A "string",number.

No string functions, 29

Here's one that uses absolutely no string-specific built-ins.

DEF A S,N
COPY T$,S,N,1?T$END

COPY is a memory copy command, capable of copying data between two compatible types. It's usually used for arrays, but it works on strings as well.

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

Ruby, 9 bytes

proc &:[]

How Ruby handles operator overloading is :+, :-, :*, :[], etc. are defined as methods, so 1+2 is essentially 1.+(2). :[] is the symbol for the subscripting "operator", which when converted to a proc calls the :[] method with the first as a receiver and the second as an argument. E.g., (proc &:[]).call("asd",0) == "asd".[](0) == "asd"[0]

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

tcl, 18

string index $s $n

Input is on the variables s and n

Output is the return of the script

demo — Iterates a list with all test case pairs and outputs them to console.

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

x86 Machine Code, 13 bytes

8B 44 24 04 03 44 24 08 8A 08 8A C1 C3

Which disassembles to:

  00000000: 8B 44 24 04        mov         eax,dword ptr [esp+4]
  00000004: 03 44 24 08        add         eax,dword ptr [esp+8]
  00000008: 8A 08              mov         cl,byte ptr [eax]
  0000000A: 8A C1              mov         al,cl
  0000000C: C3                 ret
\$\endgroup\$
0
\$\begingroup\$

Excel, 13 bytes

=MID(B1,A1,1)

1-indexed n in A1. Text in B1.

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

Husk, 1 byte

Another built-in, 1-indexed:

!

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.