# Element of string at specified index

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.

• 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. – Shaggy May 13 '17 at 14:11
• @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. – Martin Ender May 13 '17 at 14:15

# MATL, 1 byte

)


Try it online!

Well, hard to make it much simpler. ) indexes the first input, using the second input value. This is 1-indexed.

## Alice, 5 bytes

I&IO@


Try it online!

As usual it's much shorter if we avoid Ordinal mode and use an abysmal input format. Here, the first character's code point is used as the integer input. The remainder of the input is the string. The index is 1-based.

### Explanation

I   Read a character and push its code point.
&I  Read that many more characters and push them.
O   Output the last one we read.
@   Terminate the program.

• abysmal - I thought you made it xD – Stephen May 13 '17 at 12:29
• @StephenS You mean I proposed this I/O format on meta? Yeah, I did, but mostly for languages that would have to implement their own decimal integer parser/renderer each time they compete in a challenge with numerical I/O, so they would likely just skip those entirely. But it has the unfortunate side effect that in some languages which can read and write decimal quite easily it's still shorter to use code points instead. – Martin Ender May 13 '17 at 13:58

# Python, 15 bytes

str.__getitem__


or

lambda s,i:s[i]


Both take 2 arguments: the string and the index. 0-indexed.

• I'm surprised both methods have the same length. – Leaky Nun May 13 '17 at 10:48

## Haskell, 4 bytes

(!!)


0-based indexing. Usage example: (!!) "Hello" 1-> 'e'.

# Octave, 10 bytes

@(s,n)s(n)


Takes a string s, and a number n as input, and returns the nth character of s.

# Retina, 2820 19 bytes

Saved 8 bytes thanks to @MartinEnder by not using balancing groups

Saved 1 byte thanks to @mbomb007 by using ^.+ instead of ^\d+

^.+
$* +1¶. ¶ !1.  Try it online! The program is 0-indexed. • Change \d to . to save a byte. – mbomb007 May 19 '17 at 21:23 • @mbomb007 Thanks for the tip :) – Cows quack May 20 '17 at 4:52 # 05AB1E, 1 byte 0-indexed. è  Try it online! ## Alice, 10 bytes /@!O?]& I  Try it online! Expects the string on the first line and the 0-based index on the second line. ### Explanation Despite its wealth of built-ins, string indexing doesn't exist in Alice. The reason is that it requires both an integer and a string parameter, and all commands in Alice are strictly integers to integers or strings to strings. In general, the main way to perform any operations on strings that require or result in integers is to store the string on the tape in Ordinal mode, which you can then manipulate with integers in Cardinal mode. / Reflect to SE. Switch to Ordinal. While in Ordinal mode, the IP bounces diagonally up and down through the program. I Read one line from STDIN and push it. ! Store the string on the tape. This writes the character codes into consecutive tape cells starting at the tape head. (It also writes a -1 at the end as a terminator, but the tape is initialised to -1s anyway). The next few commands are junk that luckily doesn't affect the program: ? Load the string from the tape and push it to the stack again. & Fold the next command over this string. That is, for each character in the string, push that character, then execute the command. ? So we're folding "load" over the string itself. So if the string is "abc" we'll end up with "a" "abc" "b" "abc" "c" "abc" on the stack. ! Store the top copy of "abc" on the tape (does nothing, because it's already there). Now the relevant part of the program continues. I Read another line from STDIN, i.e. the string representation of the index. / Reflect to W. Switch to Cardinal. The IP wraps to the last column. & Implicitly convert the string to the integer value it represents and repeat the next command that many times. ] Move the tape head right that many cells. Note that Ordinal and Cardinal mode have separate tape heads, but they are initialised to the same cell. ? Load the value from that cell, which is the code point of the character at the given index. O Print the corresponding character. ! This discards or converts some of the strings on the stack and writes some value back to the tape, but it's irrelevant. @ Terminate the program.  • "Despite its wealth of built-ins, string indexing doesn't exist in Alice." >_> – Leaky Nun May 13 '17 at 10:49 • @LeakyNun If you think that's bad, there's also no built-in to get a string's length. ;) – Martin Ender May 13 '17 at 10:52 # Jelly, 1 byte ị  Try it online! # Prolog (SWI), 40 37 bytes q(L,N,A):-nth0(N,L,X),char_code(A,X).  Try it online! # Brachylog, 2 bytes ∋₎  Try it online! ### Explanation ∋ unifies its output with an element of the Input. With ₎ as subscript, it will unify its output with the Ith element of S, with [S,I] as input. # Cubix, 8 bytes t@poIA//  This solution is 1-indexed. The input should consist of a number first, then a separator (that is not a digit or a .) and then the string. Try it online! ## CJam, 3 bytes {=}  Try it online! = is the built-in for list/string indexing. # Japt, 2 bytes gV  This solution is 0-indexed. Try it online! # S.I.L.O.S, 43 bytes loadLine readIO a=256+i a=get a printChar a  Try it online! Simple enough. • SILOS is back \o/ – Leaky Nun May 13 '17 at 11:42 • Yeah, I'm trying to answer as many callenges as possible, including the windows loading screen one. I like the point it's at in terms of graphical output, and libraries, but I still would like to develope a compression scheme to try and get it competitive. Essentially the int[] it compiles to can be generated through reading a byte stream. @LeakyNun – Rohan Jhunjhunwala May 13 '17 at 11:43 # BF, 9 bytes ,[->,<]>.  The index is taken via the character code of a char (like the Alice submission). Following that, we have the string. Try it online! The TIO link uses a Bash wrapper and the input can be changed in the header file (the reason for the wrapper is so that we can see the bytes). • Legit TIO hacking :p – Leaky Nun May 13 '17 at 13:06 • @LeakyNun I used the wrapper for BF. – Cows quack May 13 '17 at 13:08 • I did say it is legit. – Leaky Nun May 13 '17 at 13:08 • Is there a way to do input to other TIO languages like that? Like SMBF? – mbomb007 May 19 '17 at 21:25 • @mbomb007 You should be able to do that for other languages by using their wrappers. Here's the wrapper for SMBF – Cows quack May 20 '17 at 4:53 # JavaScript, 11 10 bytes s=>n=>s[n]  Uses 0-based indexing. -1 byte thanks to @Leaky Nun f= s=>n=>s[n] console.log(f("abcde")(0)); console.log(f("abcde")(1)); console.log(f("a != b")(2)); console.log(f("+-*/")(3)); console.log(f("314159")(4)); • you can use currying s=>i=>s[i] to save a byte – Leaky Nun May 13 '17 at 10:40 • Every time I see answers like this it annoys me because I know the C# version is always one byte longer for the semi colon on the end. And that is indeed the case here – TheLethalCoder May 14 '17 at 8:37 # ><>, 13 + 1 = 14 bytes +1 for -v flag to take input :?!\i~1- io;\  Thanks to @steenbergh for notifying me about the -v flag and saving me 3 bytes! Input the index with the command line argument -v [index] (0-indexed) and input the string through stdin. Try it online! ### Explanation The stack starts with the index on top. : duplicates it. ? ignores the next character if the index is 0. (Popping it off the stack) If it is zero, \ reflects the direction to go down. Then, it is reflected to the right with the next \. It wraps around and executes input a character, output it and ; halts execution. If not, ! skips the next instruction, so it doesn't go down. i~ inputs a character and then immediately discards it. 1 pushes 1. - subtractes 1 from the index, so one character in the input is consumed and the index is decremented. The program loops around back to the :. • There is the -v <x> command line parameter, which initialises the stack to hold <x> on program start. Try it online – steenbergh May 13 '17 at 15:19 # Carrot, 16 bytes $^//.{#}/S1//.$/  Try it online! The input format is as such: string index  And the program is 1-indexed. ### Explanation Carrot has several global variables, one for each type: string, float and array (others to be implemented soon). The program starts in string-mode, where all the operators will affect the global string variable. And I call these variables the "stack". (Example input: abcdef\n3) $                          Get the first line of the input and set the stack-string to this value
^                          Exit caret-mode
stack-string = "abcdef"
/                          Operator (behaves differently depending on the argument)
/.{#}/                     And the argument to this operator is a regex, so this program gets the matches of this regex into the stack-array
.                          Any character
{#}                       Pops a line from the input. So now this evaluates to # of any character where # is the second line of the input (in this case, 3)
stack-array = ["abc"]
And now we just need to get the last character in this string, but first
S1                         Join the array on the number 1 and set this to the stack-string. Because the array only contains one element, the number 1 does not appear in the stack-string.
stack-string = "abc"
/                          Operator; because the argument is a regex, this retrieves the matches of the regex:
/.$/ Get the last character in the string stack-array = ["c"]  Now this returns a one element array containing a string of length one, but it is shown as a string in the website. If we really wanted to give the result as a string, we could easily do S"," at the end, but it doesn't matter because the output still looks the same on the interpreter. ## Batch, 32 bytes @set/ps= @call echo(%%s:~%1,1%%  Reads s from STDIN and takes n as a command-line parameter. # GolfScript, 7 4 bytes ~1/=  Try it online! I suck in GolfScript, so I value Martin Ender's help. • There's no need for the [. – Martin Ender May 13 '17 at 10:58 • But in general if you want characters from strings, you just split the string first instead of converting the code point back: ~1/= – Martin Ender May 13 '17 at 10:58 • @MartinEnder And that's how you beat Alice up... – Erik the Outgolfer May 13 '17 at 10:59 # Turtlèd, 9 bytes !?:[*l+].  Try it online! ## explanation: First off, Turtlèd is grid based, with a turtle thing. There are grid cells the turtle can move left, up, down, and right on, and can write things on the grid cells. [the first grid cell the turtle starts on is marked with a *] ! input the string into the string variable ? input the number into the number variable : this command takes the number variable and moves right that many. hence this moves right by the amount inputted [* ] this is an until loop. the * there means that until the turtle ends the loop on a grid cell with * written on it (that is, the first cell), it will execute the code inside again and again l+ the code inside the while loop. the l moves the turtle left, and the + increments the string pointer. the string pointer is used with the string var; when you want to write something from the string, you use ., which writes the pointed char. the pointed char is the n-th character of the string, n being the value of the string pointer. this code will execute until the l moves the turtle back on to the origin cell. since we moved right by the number inputted, this will increase the string pointer (which starts at 1) by the amount inputted. . write the pointed char, which was dealt with in the previous comment. if 0 is inputted, turtle stayed on the origin square, and executed none of the loop, and turtle writes the first char of string input. if 1 is inputted, turtle moved one right, moved one left and incremented string pointer once, which means the second char is written. and so on. [the char of input has been written over the origin square] [implicitly the grid is outputted, which has spaces and blank lines taken out] [this is the requested char outputted, plus an unavoidable trailing newline due to how I made the interpreter. sue me]  ## Clojure, 3 nth  :P What can you do when there is a built-in for this? This works on lists, vectors, strings and sequences. It is either O(1) or O(n), depending on the used datatype. # sed, 31 bytes : /^1/{s:1 .: :;b} s: (.).*:\1:  Try it online! Input: index and the string, separated by one space. Index in unary, but zero-based. # Dyvil, 4 Bytes _[_]  Creates an anonymous function that takes a String and an int and returns a char. Usage: let f: (String, int) -> char = _[_] print f("abc", 1) // b  # Pip, 3 bytes a@b  This is 0-based. Try it online! ## QBasic 4.5, 24 bytes INPUT a$,b:?MID$(a$,b,1)


Pretty straightforward.

# Vim, 8 bytes

DJ@"|xVp


Since V is backwards compatible, you can Try it online!

# Mathematica, 18 bytes

#~StringTake~{#2}&


Basic solution, but unfortunately the function name is quite long.

## C#, 11 bytes

s=>n=>s[n];